原型 - $() 方法
最常用的便捷功能 $() 可提供获取 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_utility_methods.htm
广告