javascript学习笔记--02

js用法
用法比较简单两句话:

  1. HTML 中的脚本必须位于 <script> 与 </script> 标签之间
  2. 脚本可被放置在 HTML 页面的 <body>和 <head>部分中
    需要指出的是脚本要使用<script> 与 </script> 标签,并且脚本内容要放在标签中间;
    另外,标本放在<body> 与 </body> 或者<head> 与 </head>中间都可以。
    例如,参考

    a. script标签位于body中,点击按钮button触发修改p标签内容

<!DOCTYPE html>
<html>
<body>
    <p id="demo">change me</p>
    <button type="button" onclick="myFunction()">尝试一下</button>
    <script>
     function myFunction()
    {
    document.getElementById("demo").innerHTML="js in body";
    }
    </script>
</body>
</html>

b. script标签位于head中,点击按钮button触发修改p标签内容

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
    <script>
        function myFunction()
        {
        document.getElementById("demo").innerHTML="js in body";
        }
    </script>
</head>
<body>
    <p id="demo">change me</p>
    <button type="button" onclick="myFunction()">尝试一下</button>  
</body>
</html>

需要注意的是,那些老旧的实例可能会在 <script> 标签中使用 type=”text/javascript”。现在已经不必这样做了。

通常为了书写条理,我们把<script> 写在<head>中。
另外,也是比较常用的就是js单独放在一个XXX.js的文件中通过调用获得
例如,

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
    <script src="myScript.js"></script>
</head>
<body>  
<h1>引用外部js</h1>
<p id="demo">显示js</p>
<button type="button" onclick="myFunction()">点击这里</button>
<p><b>注释:</b>myFunction 保存在名为 "myScript.js" 的外部文件中。</p>
</body>
</html>

myScript.js中的代码为

function myFunction()
{
    document.getElementById("demo").innerHTML="js test";
}

实际应用中,会把<script>标签放在<head>标签中,并通过引入外部js方式,这么做的好处是条理方便。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值