参考childNodes(Javascript)

时间:2015-05-04 08:45:44

标签: javascript dom child-nodes

此示例中的游戏具有可变数量的玩家。需要为每个玩家跟踪得分。该示例设法创建所需的HTML,但我不确定如何引用每个孩子。这是HTML:

var players=prompt("Number of players?",2);

oldNode = document.getElementById("scoreHolder");

for (x=1;x<players;x++) {
  newNode = oldNode.cloneNode(true);
  document.documentElement.appendChild(newNode);	
}

var c=document.getElementById("scoreHolder").childNodes;
c[1].style.backgroundColor = "yellow";
c[2].style.backgroundColor = "blue";
<div id="scoreHolder">Player 1 score: <span id="score">0<span></div>

此示例将HTML黄色的第一行部分转换为黄色,但对其他行不执行任何操作。如何引用它们以便我可以更新每个玩家的分数?

2 个答案:

答案 0 :(得分:0)

<body>
    <!-- add name attribute -->
    <div id="scoreHolder" name="scoreHolder">Player 1 score: <span id="score">0<span></div>
</body>
<script type="text/javascript">
    var players=prompt("Number of players?", 2);

        oldNode = document.getElementById("scoreHolder");

        for (var x=1;x<players;x++) {
          newNode = oldNode.cloneNode(true);
          newNode.id="newId"+x; // reassign the new id
          document.documentElement.appendChild(newNode);    
        }

        // use getElementsByName
        var c=document.getElementsByName("scoreHolder");
        c[0].style.backgroundColor = "yellow";
        c[1].style.backgroundColor = "blue";
</script>

答案 1 :(得分:-1)

这样做用于循环:

for( var i = 0; i < c.length; i++ ){
   if( i%2 == 1 )
       node[i].style.backgroundColor = "yellow";
   else    
       node[i].style.backgroundColor = "blue";
}

<强>更新 我对索引犯了错误。尝试更新一个

更新2

您遇到函数document.getElementById("scoreHolder")的问题 - 它只返回一个元素,因此请尝试将类添加到#scoreHolder和document.getElementsByClassName并从附加元素中删除ID