如何写一段JS代码并运行

Js入门与实战 admin 391浏览

1.将js代码写在html行内

<input type="button" name="" id="" value="按钮" onclick="alert(123)"/>

2.将js代码写在script标签中

<script type="text/javascript">
alert('hello world')
</script>

3.写在外部js文件中,在页面引入

<script src="./main.js"></script>

main.js文件alert('hello world')

注意点:将外部的js代码引入后执行,script标签中不需要再写入其他js代码,写了也不生效.

如果外部引入的方式加载js代码,script标签内不需要再写代码,如果写了不会报错,也不会运行.

单独js文件中的代码是不能直接在浏览器中打开运行对的;需要将js文件引入到html中,浏览器打开html后js代码才会被运行.

转载请注明:大灰牛博客 » 如何写一段JS代码并运行