Javascript计数器变量不显示正确的值

时间:2015-04-09 00:19:38

标签: javascript

我有一个全局计数器变量,当我在HTML中调用它时,我没有获得更新的值。我只获得实例化的值。 当我打电话给它时,我总是得到1.我需要它来显示2,3,4等......

  <script type="text/javascript">
    var counter = 1;
    function moreFields() {
      counter++;
      var newFields = document.getElementById('readroot').cloneNode(true);
      newFields.id = '';
      newFields.style.display = 'block';
      var newField = newFields.childNodes;
      for (var i=0;i<newField.length;i++) {
        var theName = newField[i].name
        if (theName)
          newField[i].name = theName + counter;
      }
  </script>
</fieldset>
<span id="writeroot"></span>
<fieldset id="readroot" style="display: none">
  <legend>Options For FieldSet # <script> document.write(counter.value);</script></legend>
</fieldset>

1 个答案:

答案 0 :(得分:0)

正如Brad Christie评论的那样, document.write(counter.value);只发生一次,并且在调用函数moreFields()之前发生。

相反,我建议在legend标记内创建一个span(或基本上任何html元素)。

例如:

<legend>Options For FieldSet # <span id="counterDisplay"></span></legend>

然后,您可以通过其类访问div,并在必要时更新该值。

例如,在代码的开头你可以这样做:

<script type="text/javascript">
    var counter = 1;
    document.getElementById("counterDisplay").innerHTML = counter;

同样,在函数moreFields中,你可以这样做:

function moreFields() {
    counter++;
    var newFields = document.getElementById('readroot').cloneNode(true);
    newFields.id = '';
    newFields.style.display = 'block';
    var newField = newFields.childNodes;
    for (var i=0;i<newField.length;i++) {
        var theName = newField[i].name
        if (theName)
            newField[i].name = theName + counter;
    }
    document.getElementById("counterDisplay").innerHTML = counter;
}

最后,您可以像这样重写代码块:

<script type="text/javascript">
    var counter = 1;
    document.getElementById("counterDisplay").innerHTML = counter;
    function moreFields() {
        counter++;
        var newFields = document.getElementById('readroot').cloneNode(true);
        newFields.id = '';
        newFields.style.display = 'block';
        var newField = newFields.childNodes;
        for (var i=0;i<newField.length;i++) {
            var theName = newField[i].name
            if (theName)
                newField[i].name = theName + counter;
        }
        document.getElementById("counterDisplay").innerHTML = counter;
    }
</script>
<span id="writeroot"></span>
<fieldset id="readroot" style="display: none">
    <legend>Options For FieldSet # <span id="counterDisplay"></span></legend>
</fieldset>