javascript 为什么 getElementByClassName -> getElementsByTagName -> setAttribute 不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3797857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why doesn't getElementByClassName -> getElementsByTagName -> setAttribute work?
提问by Martin
I want open certain links in a new tab. Since I can't set it directly into the <a>tag, I want to put the link into <span>tags with a certain class name and set the target attribute via JavaScript.
我想在新标签页中打开某些链接。由于无法直接设置到<a>标签中,我想将链接放入<span>具有特定类名的标签中,并通过JavaScript设置目标属性。
I thought this would be easy, but I can't get it working:
我认为这很容易,但我无法让它工作:
addOnloadHook(function () {
document.getElementByClassName('newTab').getElementsByTagName('a').setAttribute('target', '_blank');
});
<span class="newTab"><a href="http://www.com">Link</a></span>
What am I doing wrong?
我究竟做错了什么?
回答by Lekensteyn
document.getElementByClassNamedoes not exist, the correct function is document.getElementsByClassName(note the extra s). It returns an array of matching nodes, so you've to give an index:
document.getElementByClassName不存在,正确的函数是document.getElementsByClassName(注意额外的s)。它返回一个匹配节点的数组,所以你必须给出一个索引:
addOnloadHook(function () {
document.getElementsByClassName('newTab')[0].getElementsByTagName('a')[0].setAttribute('target', '_blank');
});
回答by Jonas
but you might need to iterate through every span with the specified class ('newTab') on the page for it to work:
但是您可能需要在页面上使用指定的类('newTab')遍历每个跨度才能使其工作:
addOnLoadHook(function(){
var span = document.getElementsByClassName('newTab');
for(var i in span) {
span[i].getElementsByTagName('a')[0].setAttribute('target','_blank');
}
});
in case you'll have more than 1 anchor tag in a span you'd also have to iterate through the anchor tags like this:
如果您在一个跨度中有超过 1 个锚标记,您还必须像这样遍历锚标记:
addOnLoadHook(function(){
var span = document.getElementsByClassName('newTab');
for(var i in span){
var a = span[i].getElementsByTagName('a');
for(var ii in a){
a[ii].setAttribute('target','_blank');
}
}
});

