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

myElement.innerText = "foo";

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


当前回答

像这样的东西怎么样?

//$elem is the jQuery object passed along.

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

**我需要把我的大写。

其他回答

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

myElement.innerText = myElement.textContent = "foo";

编辑(感谢Mark Amery在下面的评论):只有当您确信没有代码会像jQuery那样依赖于检查这些属性是否存在时,才会这样做。但如果你正在使用jQuery,你可能只需要使用"text"函数并执行$('#myElement').text('foo'),就像其他答案显示的那样。

这是我对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;我在上面没有评论。

如果您只需要设置文本内容而不需要检索,这里有一个简单的DOM版本,您可以在任何浏览器上使用;它既不需要IE的innerText扩展,也不需要DOM Level 3 Core textContent属性。

function setTextContent(element, text) {
    while (element.firstChild!==null)
        element.removeChild(element.firstChild); // remove all existing content
    element.appendChild(document.createTextNode(text));
}

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

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