JavaScript getAttribute 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4595413/
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
JavaScript getAttribute not working
提问by icant
var objects = document.getElementsByTagName('object');
for (var i=0, n=objects.length;i<n;i++) {
objects[i].style.display='none';
var swfurl;
var j=0;
while (objects[i].childNodes[j]) {
if (objects[i].childNodes[j].getAttribute('name') == 'movie') {
/* DO SOMETHING */
}
j++;
}
var newelem = document.createElement('div');
newelem.id = '678297901246983476'+i;
objects[i].parentNode.insertBefore(newelem, objects[i]);
new Gordon.Movie(swfurl, {id: '678297901246983476'+i, width: 500, height: 400});
}
It says that getAttribute is not a function of childNodes[j]. What's wrong? I don't see the point.
它说 getAttribute 不是 childNodes[j] 的函数。怎么了?我看不出重点。
回答by T.J. Crowder
Remember that childNodesincludes text nodes (and comment nodes, if any, and processing instructions if any, etc.). Be sure to check the nodeTypebefore trying to use methods that only Elementshave.
请记住,这childNodes包括文本节点(和注释节点,如果有的话,以及处理指令,如果有的话,等等)。nodeType在尝试使用只有Elements 的方法之前一定要检查。
Update: Here in 2018, you could use childreninstead, which only includes Elementchildren. It's supported by all modern browsers, and by IE8-IE11. (There are some quirks in older IE, see the link for a polyfill to smooth them over.)
更新:在 2018 年,您可以children改为使用,它只包括Element儿童。所有现代浏览器和 IE8-IE11 都支持它。(旧 IE 中有一些怪癖,请参阅 polyfill 的链接以平滑它们。)
回答by Tim Down
Check the nodeTypeproperty is 1 (meaning the node is an element) before calling element-specific methods such as getAttribute(). Also, forget getAttribute()and setAttribute(): you almost never need them, they're broken in IE and they don't do what you might think. Use equivalent DOM properties instead. In this case:
检查nodeType属性为1(意味着该节点是一个元素)调用特定元素的方法,例如之前getAttribute()。另外,忘记getAttribute()和setAttribute():你几乎从不需要它们,它们在 IE 中坏了,它们不会像你想象的那样做。请改用等效的 DOM 属性。在这种情况下:
var child = objects[i].childNodes[j];
if (child.nodeType == 1 && child.name == 'movie') {
/* DO SOMETHING */
}
回答by volpav
What browser are you using ? If it's IE then you need to use readAttributeinstead.
你使用的是什么浏览器 ?如果是 IE,则需要readAttribute改用。
-- Pavel
-- 帕维尔

