我想打印具有类名“test”的每个元素的Id。现在没有什么打印。我想这对打印在javascript中打印一个类的所有id名称
myAnchor
SecondId
我离开了我的意见在那里展示如何的标识可以通过访问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。 – RobG
每次迭代都覆盖'demo'。另外,在for循环中使用'var'或者创建一个隐式的全局变量。 –