编写 JS 代码的位置

1. 节点及其类型:

  1. 元素节点
  2. 属性节点: 元素的属性, 可以直接通过属性的方式来操作.
  3. 文本节点: 是元素节点的子节点, 其内容为文本.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    //1. 当整个 HTML 文档完全加载成功后触发 window.onload 事件. 
    //事件触发时, 执行后面 function 里边的函数体. 
    window.onload = function(){
        //2. 获取所有的 button 节点. 并取得第一个元素
        var btn = document.getElementsByTagName("button")[0];
        //3. 为 button 的 onclick 事件赋值: 当点击 button 时, 执行函数体
        btn.onclick = function(){
            //4. 弹出 helloworld
            alert("helloworld");
        }
    }    
</script>
</head>
<body>
    
    <button>ClickMe</button>
    
</body>
</html>

前端历险记--JavaScript DOM编程

 

 

 

2. 在 html 文档的什么位置编写 js 代码?

0). 直接在 html 页面中书写代码.

<button id="button" onclick="alert('hello world');">Click Me!</button>

缺点:

① js 和 html 强耦合, 不利用代码的维护
②若 click 相应函数是比较复杂的, 则需要先定义一个函数, 然后再在 onclick 属性中完成对函数的引用, 比较麻烦

1). 一般地, 不能在 body 节点之前来直接获取 body 内的节点, 因为此时 html 文档树还没有加载完成,

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    
    //1. 获取 button
    var btns = document.getElementsByTagName("button");
    alert(btns.length);
    
    //2. 为 button 添加 onclick 响应函数
    btns[0].onclick = function(){
        alert("helloworld!!");
    }

</script>
</head>
<body>
    
    <button>ClickMe</button>
    
</body>
</html>
View Code

相关文章: