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