我有一些JavaScript代码,在IE中包含以下内容:
myElement.innerText = "foo";
然而,'innerText'属性似乎在Firefox中不起作用。Firefox中有类似的吗?或者是否可以使用更通用的跨浏览器属性?
我有一些JavaScript代码,在IE中包含以下内容:
myElement.innerText = "foo";
然而,'innerText'属性似乎在Firefox中不起作用。Firefox中有类似的吗?或者是否可以使用更通用的跨浏览器属性?
当前回答
jQuery提供了一个.text()方法,可以在任何浏览器中使用。例如:
$('#myElement').text("Foo");
其他回答
更新:我写了一篇博客文章,详细介绍了所有的区别。
Firefox使用W3C标准Node::textContent,但它的行为与MSHTML的专有内层文本(在几十个其他MSHTML特性中也被Opera复制了一段时间)“略有不同”。
首先,textContent的空白表示不同于innerText。其次,更重要的是,textContent包含所有SCRIPT标记内容,而innerText不包含。
只是为了让事情更有趣,Opera -除了实现标准的textContent -决定还添加MSHTML的innerText,但将其更改为textContent -即包括SCRIPT内容(事实上,textContent和innerText在Opera中似乎产生相同的结果,可能只是别名彼此)。
textContent是Node接口的一部分,而innerText是HTMLElement的一部分。例如,这意味着你可以从文本节点中“检索”textContent,但不能检索innerText:
var el = document.createElement('p');
var textNode = document.createTextNode('x');
el.textContent; // ""
el.innerText; // ""
textNode.textContent; // "x"
textNode.innerText; // undefined
最后是Safari 2。x也有bug的innerText实现。在Safari中,只有当元素为时,innerText才能正常工作 没有隐藏(通过风格。Display == "none")或从文档中孤立。否则,innerText结果为空字符串。
我正在使用textContent抽象(以解决这些缺陷),但结果证明它相当复杂。
最好的办法是先定义您的确切需求,然后从那里开始。通常可以简单地从元素的innerHTML中剥离标签,而不是处理所有可能的textContent/innerText偏差。
当然,另一种可能是遍历DOM树并递归地收集文本节点。
在这里找到这个:
<!--[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]-->
如果您只需要设置文本内容而不需要检索,这里有一个简单的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));
}
这是我对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;我在上面没有评论。
Firefox使用w3c兼容的textContent属性。
我猜Safari和Opera也支持这个属性。