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

myElement.innerText = "foo";

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


当前回答

像这样的东西怎么样?

//$elem is the jQuery object passed along.

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

**我需要把我的大写。

其他回答

Firefox使用w3c兼容的textContent属性。

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

一个非常简单的Javascript行可以在所有主要浏览器中获得“非标记”文本……

var myElement = document.getElementById('anyElementId');
var myText = (myElement.innerText || myElement.textContent);

在这里找到这个:

<!--[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]-->

这是我对innerText, textContent, innerHTML和value的经验:

// elem.innerText = changeVal;  // works on ie but not on ff or ch
// elem.setAttribute("innerText", changeVal); // works on ie but not ff or ch
// elem.textContent = changeVal;  // works on ie but not ff or ch
// elem.setAttribute("textContent", changeVal);  // does not work on ie ff or ch
// elem.innerHTML = changeVal;  // ie causes error - doesn't work in ff or ch
// elem.setAttribute("innerHTML", changeVal); //ie causes error doesn't work in ff or ch
   elem.value = changeVal; // works in ie and ff -- see note 2 on ch
// elem.setAttribute("value", changeVal); // ie works; see note 1 on ff and note 2 on ch

Ie = Ie, ff = firefox, ch =谷歌chrome。 注1:ff工作直到值被backspace删除-见Ray Vega上面的注释。 注2:工作在chrome -更新后,它是不变的,然后你点击离开,点击回到字段和值出现。 其中最好的是elem。value = changeVal;我在上面没有评论。

根据Prakash K的回答,Firefox不支持innerText属性。所以你可以简单地测试用户代理是否支持这个属性,并按照下面的步骤进行:

function changeText(elem, changeVal) {
    if (typeof elem.textContent !== "undefined") {
        elem.textContent = changeVal;
    } else {
        elem.innerText = changeVal;
    }
}