我正在练习DOM Scripting(没有现实生活中的问题,而是实践和理论,我知道如何用jQuery实现这一点)所以,我正在努力改进和理解以下内容:
我有一些类的链接,我附加事件:
<a href="http://www.google.com" class="popup">click</a>
<a href="http://www.test.com" class="popup">click2</a>
<a href="http://www.abc.com" class="popup">click3</a>
<a href="http://www.google.com" class="no">click4</a>
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
window.onload = prepareLinks;
function prepareLinks() {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
if (links[i].getAttribute("class") == "popup") {
links[i].onclick = function () {
popUp(this.getAttribute("href"));
return false;
}
}
}
}
function popUp(winURL) {
window.open(winURL, "popup", "width=320,height=480");
}
Run Code Online (Sandbox Code Playgroud)
这很好.我基本上从一本书中得到了它.现在我想通过使用getElementsByClassName来改进它.我继续写道:
window.onload = prepareLinks;
function prepareLinks() {
var links = document.getElementsByTagName("a");
var popups = links.getElementsByClassName("popup");
for (var i = 0; i < popups.length; i++) {
popups[i].onclick = function () {
popUp(this.getAttribute("href"));
return false;
}
}
}
function popUp(winURL) {
window.open(winURL, "popup", "width=320,height=480");
}
Run Code Online (Sandbox Code Playgroud)
但我收到错误:未捕获TypeError:对象#没有方法'getElementsByClassName'
显然,链接是NodeList,因此我不能在其上使用getElementsByClassName.我真的不明白......你能帮我解决这个问题,以及脚本的第一个版本是否合适?(表现明智).谢谢.
您不能使用getElement*函数来相互过滤,因为它们不在列表上运行,并且它们也不会在结果中返回原始节点.如果您需要同时过滤多个条件,请querySelectorAll改为使用,例如document.querySelectorAll("a.popup").
| 归档时间: |
|
| 查看次数: |
5063 次 |
| 最近记录: |