返回到:Prototype – 实用方法
最常用和方便的函数 $() 提供了一种获取 DOM 元素句柄的简单方法。
语法
$(id | element) OR $((id | element)...)
返回值
- 找到 HTMLElement。
- 如果找到多个元素,则返回 HTML 元素数组。
这是一种编写 Javascript 语句以获取 DOM 节点的旧方法。
node = document.getElementById("elementID");
使用 $(),我们可以将其缩短如下 –
node = $("elementID");
例子
HTML
x
25
25
1
<html>
2
<head>
3
<title>Prototype examples</title>
4
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
5
6
<script>
7
function test() {
8
node = $("firstDiv");
9
alert(node.innerHTML);
10
}
11
</script>
12
</head>
13
14
<body>
15
<div id = "firstDiv">
16
<p>This is first paragraph</p>
17
</div>
18
19
<div id = "secondDiv">
20
<p>This is another paragraph</p>
21
</div>
22
23
<input type = "button" value = "Test $()" onclick = "test();"/>
24
</body>
25
</html>
使用 $() 获取多个值
$() 函数也比document.getElementById()更强大,因为检索多个元素的能力内置于函数中。
此函数的另一个好处是您可以传递 id 字符串或元素对象本身,这使得此函数在创建也可以采用任何一种参数形式的其他函数时非常有用。
例子
在这个例子中,我们看到 $() 函数现在返回一个元素数组,然后可以用一个简单的 for循环访问它。
HTML
xxxxxxxxxx
1
28
28
1
<html>
2
<head>
3
<title>Prototype examples</title>
4
<script type = "text/javascript" src = "/javascript/prototype.js"></script>
5
6
<script>
7
function test() {
8
allNodes = $("firstDiv", "secondDiv");
9
10
for(i = 0; i < allNodes.length; i++) {
11
alert(allNodes[i].innerHTML);
12
}
13
}
14
</script>
15
</head>
16
17
<body>
18
<div id = "firstDiv">
19
<p>This is first paragraph</p>
20
</div>
21
22
<div id = "secondDiv">
23
<p>This is another paragraph</p>
24
</div>
25
26
<input type = "button" value = "Test $()" onclick = "test();"/>
27
</body>
28
</html>
返回到:Prototype – 实用方法
阅读剩余 89%
作者:terry,如若转载,请注明出处:https://www.web176.com/prototype_api/8959.html