动态修改的输入值未反映在DOM中

时间:2011-04-17 21:08:31

标签: javascript jquery dynamic

如何让DOM反映修改后的输入值?

<div>
  <input value='0'>
</div>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js'></script>

<script>
setInterval(function() {
  $('input').val(parseInt($('input').val()) + 1)
  console.log('div.html(): ', $('div').html())
}, 1000)
</script>

3 个答案:

答案 0 :(得分:5)

尝试直接更改DOM。例如:

<div id="myDiv">
  <input id="myInput" value='0'>
</div>

<script>
setInterval(function() {
    var v = parseInt(document.getElementById("myInput").value) + 1;
    document.getElementById("myInput").setAttribute("value",v);
}, 1000);
</script>

<input type="button" onclick="javascript:alert(document.getElementById('myDiv').innerHTML);" value="Click to see DOM" />

答案 1 :(得分:4)

以下似乎对我有用:

http://jsfiddle.net/h8AP8/1/

所有这些都归功于gnarf和他的formhtml:

jQuery html() in Firefox (uses .innerHTML) ignores DOM changes

所以修改后的代码将是:

<div>
  <input value='0'>
</div>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js'></script>

<script>
(function($) {
  var oldHTML = $.fn.html;

  $.fn.formhtml = function() {
    if (arguments.length) return oldHTML.apply(this,arguments);
    $("input,button", this).each(function() {
      this.setAttribute('value',this.value);
    });
    $("textarea", this).each(function() {
      // updated - thanks Raja!
      this.innerHTML = this.value;
    });
    $("input:radio,input:checkbox", this).each(function() {
      // im not really even sure you need to do this for "checked"
      // but what the heck, better safe than sorry
      if (this.checked) this.setAttribute('checked', 'checked');
      else this.removeAttribute('checked');
    });
    $("option", this).each(function() {
      // also not sure, but, better safe...
      if (this.selected) this.setAttribute('selected', 'selected');
      else this.removeAttribute('selected');
    });
    return oldHTML.apply(this);
  };

  //optional to override real .html() if you want
  // $.fn.html = $.fn.formhtml;
})(jQuery);


setInterval(function() {
  $('input').val(parseInt($('input').val()) + 1)
  console.log('div.html(): ', $('div').formhtml())
}, 1000)
</script>

答案 2 :(得分:0)

对不起,问题不在于您提供的示例代码中。 或者当这是您网页中唯一的html时,您就会错过起始和结束标记。

这个干净的页面在我的机器上完美运行:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head></head>
    <body>
        <div><input value='0'></div>

        <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js'></script>
        <script>
        setInterval(function() {
          $('input').val(parseInt($('input').val()) + 1)
          console.log('div.html(): ', $('div').html())
        }, 1000);
        </script>
    </body>
</html>

或者您在Internet Explorer中进行测试?在这种情况下,请删除登录到错误控制台的行:

console.log('div.html(): ', $('div').html())