如何引入JavaScript代码的方式

1. 在一对script标记中写代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">
        alert('你好!');
    </script>
</body>
</html>
 
2. 在html的行内编写代码(这种方式不建议使用)
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <input type="button" value="按钮" onclick="alert('今天天气特别好!')"/>
    <script type="text/javascript">
        alert('你好!');
    </script>
</body>
</html>
 
3. 用script标签以及src属性引入指定js文件
 
建立一个js文件,内容:
 
alert('今天天气很好');
 
html文件:
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <input type="button" value="按钮" onclick="alert('今天天气特别好!')"/>
    <script type="text/javascript">
        alert('你好!');
    </script>
 <!-- 加了src之后,不能再在script标签中加内容,因为会被disable掉 -->
    <script type="text/javascript" src="js/myjs.js"></script>
 
 <!-- 1.如果JavaScript的代码出了错,会发生什么?
            它就停止执行了
         2.如果在先定义的代码出了错,会影响后面的代码么?
            不会
         3.type="text/javascript"可以不用写,不会影响代码的执行
    -->
</body>
</html>
 
posted @ 2021-04-28 22:32  #Friday  阅读(266)  评论(0)    收藏  举报