For循环填充我的div框

时间:2014-03-03 21:21:10

标签: javascript function loops for-loop

为什么这不填充我的div盒1-28请帮忙。

$(document).ready(function () {
    var $newdiv = $('div.box').text(i);
    for (var i =2; i <28; i++) {
        $newdiv = $('div.box').text(i);
        $('div.box').append($newdiv);
    }
});

3 个答案:

答案 0 :(得分:0)

你需要改变你的条件。现在,您从i=2开始,到i=27结束。更改你的for循环来改为:

for (var i=1; i<=28; i++) {
    // ...
}

答案 1 :(得分:0)

JavaScript对象通过引用传递。因此,您要更改原始DOM对象的文本, 创建新对象。请尝试以下方法:

// Shorthand for $(document).ready(function () { ... });
$(function () {
    // Create an array to store your new elements temporarily.
    var newDivs = [];
    for(var i = 1; i < 29; i++) {
        // Create your new <div> elements and push them to
        // your array. Using the following syntax for
        // creating elements allows jQuery to use
        // document.createElement internally.
        newDivs.push($('<div />', { "class": "box", "text": i }));
    }
    // Once all elements are created, append the entire
    // group to the $('div.box') element.
    $('div.box').append(newDivs);
});

答案 2 :(得分:0)

尝试这个。它已经过测试。

    <pre>

<html>
<head> 
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script> 
 <script>      
   $(document).ready(function () {
     for (var i=1; i <28; i++) {
      $('#box').append(i+" ");
      }
    });
 </script>
</head>
<body>
<style type="text/css">
#box{
    border: 1px solid red;
    height: 100px;
    width: 100px;

}
</style>
 <div id="box">
 </div>
</body>
</html>


<code>