【发布时间】:2017-02-10 21:42:47
【问题描述】:
我想打印每个类名为“test”的元素的 ID。现在什么都没有打印。我想要这个打印出来
myAnchor
SecondId
我把我的 cmets 放在那里是为了展示如何通过访问 Id 名称来打印 Id
这是我的脚本
<!DOCTYPE html>
<html>
<body>
<p><a id="myAnchor" class="test" href="http://www.w3schools.com/">W3Schools</a></p>
<p><a id="SecondId" class="test" href="http://www.w3schools.com/">Second</a></p>
<p>Click the button to display the value of the id attribute of the link above.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
//var x = document.getElementById("myAnchor");
//document.getElementById("demo").innerHTML = x.id;
var x = document.getElementByClassName("test");
for(count = 0; count < x.length; count++){
document.getElementById("demo").innerHTML = x.id;
}
}
</script>
</body>
</html>
【问题讨论】:
-
var x = document.getElementsByClassName("test");还有document.getElementById("demo").innerHTML = x[count].id; -
可能需要
...innerHTML += ...连接所有ID。 -
每次迭代都会覆盖
demo。此外,在 for 循环中使用var或创建一个隐式全局变量。
标签: javascript html class