每次循环时都通过id获取元素

时间:2013-06-05 20:55:32

标签: javascript

所以我的问题是,每当我运行这个循环时,它只会抓住第一次翻转时元素的更改。有没有办法让它每次都做出这些改变?

<script>
for ( i=0; i<5; i++){
    document.write('<div id=\"blah\" >text</div>');
    var b = document.getElementById("blah"); 
    b.style.width ="200px";      
    b.style.backgroundColor="yellow";
}
</script>

3 个答案:

答案 0 :(得分:3)

id必须在文档中是唯一的。因此问题。即使有多个匹配,DOM也只返回1个节点。

您可以这样做:

for (var i=0; i<5; i++){
    var div = '<div class="blah" >text</div>';
    div.style.width ="200px";
    div.style.backgroundColor="yellow";
    document.write(div);
}

答案 1 :(得分:2)

我有两个想法可以解决这个问题。第一种是创建元素,更改其样式并附加它。

<script type="text/javascript">
    for (var i = 0; i < 5; i++) {
        var div = document.createElement("div");
        div.style.width = "200px";
        div.style.backgroundColor = "yellow";
        document.appendChild(div);
    }
</script>

另一个想法是你不需要对DOM元素的引用,因为你只是改变了样式,所以你可以用CSS来应用这个样式。例如:

<style type="text/css">
    div.something {
        width: 200px;
        background-color: yellow;
    }
</style>

<script type="text/javascript">
    for (var i = 0; i < 5; i++) {
        document.write("<div class='something'>text</div>");
        // Or use the createElement/appendChild approach from above,
        //  where you'd need to set the div.className property as "something"
    }
</script>

答案 2 :(得分:0)

您需要将元素添加到DOM才能以后访问它。

for(var i=0;i<5;i++)
{
  //I'm not sure if you are just trying to make these changes each iteration
  //or create a new element each time. If you are trying to create a new element
  //each time. I'd def consider going a diff route i.e. use classes.
  var b;
  if( i==0 ){
    b = document.createElement("DIV"); 
    b.id = "blah";}
  else{
    b = document.getElementById("blah");}

  b.style.width ="200px";      
  b.style.backgroundColor="yellow";
}