无法获得正确的动态添加divs计数

时间:2016-03-31 14:17:52

标签: javascript html

我有一个body元素,在这个body元素中我有一个id为fullpage的子元素。此元素包含classname section的子元素。在函数load_works()中,我添加了两个section元素

<body>

    <div id="fullpage">

        <div class="section">
              <!-- Content -->
        </div>

    </div>


    <script src="js/main.js" charset="utf-8"></script>
    <script type="text/javascript">
        load_works();
    </script>


</body>

main.js的内容:

function load_works() {

    var container = document.getElementById('fullpage');

        for (var i = 0; i < 2; i++) {
            var new_section = document.createElement('div');
            new_section.className = "section";

            container.appendChild(new_section);
        }

}

问题是,当我在执行section之后尝试将getElementsByClassName()元素与load_works()计算在一起时

function some_function() {

     var sections = document.getElementsByClassName('section');
     console.log(sections.length);

}

它总是返回1,我认为这是因为我只有一个静态section元素。当然querySelectorAll()和其他get-功能也不起作用。那么,如何用纯Javascript而不是jQuery实现正确的结果呢?

1 个答案:

答案 0 :(得分:1)

您最好将所有javascript放在一个文件中,例如main.js,然后您只需在some_function()后调用load_works()

&#13;
&#13;
function load_works() {
  var container = document.getElementById('fullpage');
  for (var i = 0; i < 2; i++) {
    var new_section = document.createElement('div');
    new_section.className = "section";
    container.appendChild(new_section);
  }
}

function some_function() {
  var sections = document.getElementsByClassName('section');
  alert(sections.length);
}

load_works();
some_function();
&#13;
<div id="fullpage">
  <div class="section">
    <!-- Content -->
  </div>
</div>
&#13;
&#13;
&#13;