我想打印具有類名「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'或者創建一個隱式的全局變量。 –