Firefox中的jQuery html()(使用.innerHTML)忽略DOM更改

Jon*_*noW 21 html firefox jquery dom innerhtml

我真的很惊讶我之前没遇到过这个问题,但似乎在元素上调用jQueries .html()函数会忽略DOM中的更改,即它会返回原始源中的HTML.IE不会这样做.jQueries .html()只是在内部使用innerHTML属性.

这是否意味着发生?我使用的是Firefox 3.5.2.我在下面有一个示例,无论您将文本框值更改为什么,"container"元素的innerHTML只返回HTML标记中定义的值.该示例不使用jQuery只是为了使它更简单(使用jQuery的结果是相同的).

有没有人有一个解决方法,我可以在当前状态下获取容器的html,即包括对DOM的任何脚本更改?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <script type="text/javascript">
            <!--
            function BodyLoad(){                
                document.getElementById("textbox").value = "initial UPDATE";
                DisplayTextBoxValue();
            }

            function DisplayTextBoxValue(){
                alert(document.getElementById("container").innerHTML);             
                return false;
            }
            //-->
        </script>
    </head>
    <body onload="BodyLoad();">
        <div id="container">
            <input type="text" id="textbox" value="initial" />
        </div>
        <input type="button" id="button" value="Test me" onclick="return DisplayTextBoxValue();" />
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

gna*_*arf 36

Firefox不会根据用户输入更新DOM对象的value 属性,只是它的value 属性 - 非常快速的解决方法存在.

DOM:

function DisplayTextBoxValue(){
  var element = document.getElementById('textbox');
  // set the attribute on the DOM Element by hand - will update the innerHTML
  element.setAttribute('value', element.value);
  alert(document.getElementById("container").innerHTML);             
  return false;
}
Run Code Online (Sandbox Code Playgroud)

jQuery插件.formhtml()自动执行此操作:

(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 & Dr. Fred!
      $(this).text(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);
Run Code Online (Sandbox Code Playgroud)


Phi*_*ert 6

这是Firefox中一个已知的"问题".innerHTML的规范并不完全清楚,因此不同的浏览器供应商以不同的方式实现它.

有关此主题的讨论可以在这里找到:

http://forums.mozillazine.org/viewtopic.php?t=317838#1744233