-
节点及其类型:
1). 元素节点
2). 属性节点: 元素的属性, 可以直接通过属性的方式来操作.
3). 文本节点: 是元素节点的子节点, 其内容为文本. -
在 html 文档的什么位置编写 js 代码?
0). 直接在 html 页面中书写代码.
<button id="button" onclick="alert('hello world');">Click Me!</button>
缺点:
①. js 和 html 强耦合, 不利用代码的维护
②. 若 click 相应函数是比较复杂的, 则需要先定义一个函数, 然后再在 onclick 属性中完成对函数的引用, 比较麻烦1). 一般地, 不能在 body 节点之前来直接获取 body 内的节点, 因为此时 html 文档树还没有加载完成,
获取不到指定的节点:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
<script type="text/javascript">
var cityNode = document.getElementById("city");
//打印结果为 null.
alert(cityNode);
</script>
</head>
<body>
......
2). 可以在整个 html 文档的最后编写类似代码, 但这不符合习惯
3). 一般地, 在 body 节点之前编写 js 代码, 但需要利用 window.onload 事件,
该事件在当前文档完全加载之后被触发, 所以其中的代码可以获取到当前文档的任何节点.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Document</title>
<script type="text/javascript">
window.onload = function(){
var cityNode = document.getElementById("city");
alert(cityNode);
};
</script>
</head>
<body>
......