JavaScript 循环遍历所有带有标记名、警报的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15236049/
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 loop through all elements with tagname, alert
提问by user43107
var all = document.getElementsByTagName("a");
for (var i=0, max=all.length; i < max; i++) {
alert(x.innerHTML);
}
The purpose of this script is obvious: it tries to loop through all the elements with the tag name a
, and alert the contents of each one.
这个脚本的目的很明显:它试图遍历所有带有标签 name 的元素a
,并提醒每个元素的内容。
It doesn't run right.
It works fine, with one element, it alerts it's contents, but when there are more then one, it starts echoing undefined
for each.
它运行不正确。
它工作正常,只有一个元素,它会提醒它的内容,但是当有多个元素时,它开始undefined
为每个元素回显。
采纳答案by uoryon
you should use alert(all[i].innerHTML)
. x
is undefined
你应该使用alert(all[i].innerHTML)
. x
未定义
回答by BenM
You haven't provided a definition for x
. Try this:
您尚未提供x
. 试试这个:
var all = document.getElementsByTagName("a");
for(var i = 0, max = all.length; i < max; i++)
{
alert(all[i].innerHTML);
}
回答by ZER0
x
is obviously undefined. You need to have something like:
x
显然是未定义的。你需要有这样的东西:
var all = document.getElementsByTagName("a");
for (var i = 0, x; x = all[i++];)
alert(x.innerHTML);
However alert
in a loop is really annoying, I would suggest to use console.log
instead.
但是alert
在循环中真的很烦人,我建议console.log
改用。
Tips: in browsers that supports already for…of, such Firefox, you can simply have:
提示:在已经支持for...of 的浏览器中,比如 Firefox,你可以简单地拥有:
var all = document.getElementsByTagName("a");
for (var x of all)
console.log(x.innerHTML);
Of course you can't use that on webside across browsers, it's just something good to know in the upcoming ES6 – or if you're going to write a Firefox's extension for instance.
当然,你不能跨浏览器在 web 端使用它,在即将到来的 ES6 中了解它只是一件好事——或者如果你打算编写一个 Firefox 的扩展。