我有一些JavaScript代码,在IE中包含以下内容:

myElement.innerText = "foo";

然而,'innerText'属性似乎在Firefox中不起作用。Firefox中有类似的吗?或者是否可以使用更通用的跨浏览器属性?


当前回答

innerText已经添加到Firefox,应该在FF45版本中可用:https://bugzilla.mozilla.org/show_bug.cgi?id=264412

规范草案已经编写完成,并有望在未来被纳入HTML生活标准:http://rocallahan.github.io/innerText-spec/, https://github.com/whatwg/html/issues/465

请注意,目前Firefox、Chrome和IE实现都是不兼容的。展望未来,我们可能会看到Firefox、Chrome和Edge融合在一起,而旧的IE仍然不兼容。

参见:https://github.com/whatwg/compat/issues/5

其他回答

只是从原帖子下的评论中转发。innerHTML适用于所有浏览器。谢谢stefita。

myElement。innerHTML = "foo";

在这里找到这个:

<!--[if lte IE 8]>
    <script type="text/javascript">
        if (Object.defineProperty && Object.getOwnPropertyDescriptor &&
            !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get)
          (function() {
            var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
            Object.defineProperty(Element.prototype, "textContent",
              { // It won't work if you just drop in innerText.get
                // and innerText.set or the whole descriptor.
                get : function() {
                  return innerText.get.call(this)
                },
                set : function(x) {
                  return innerText.set.call(this, x)
                }
              }
            );
          })();
    </script>
<![endif]-->

Firefox使用w3c兼容的textContent属性。

我猜Safari和Opera也支持这个属性。

像这样的东西怎么样?

//$elem is the jQuery object passed along.

var $currentText = $elem.context.firstChild.data.toUpperCase();

**我需要把我的大写。

也可以在其他浏览器中模拟innerText行为:

 if (((typeof window.HTMLElement) !== "undefined") && ((typeof HTMLElement.prototype.__defineGetter__) !== "undefined")) {
     HTMLElement.prototype.__defineGetter__("innerText", function () {
         if (this.textContent) {
             return this.textContent;
         } else {
             var r = this.ownerDocument.createRange();
             r.selectNodeContents(this);
             return r.toString();
         }
     });
     HTMLElement.prototype.__defineSetter__("innerText", function (str) {
         if (this.textContent) {
             this.textContent = str;
         } else {
             this.innerHTML = str.replace(/&/g, '&amp;').replace(/>/g, '&gt;').replace(/</g, '&lt;').replace(/\n/g, "<br />\n");
         }
     });
 }