我有一些JavaScript代码,在IE中包含以下内容:
myElement.innerText = "foo";
然而,'innerText'属性似乎在Firefox中不起作用。Firefox中有类似的吗?或者是否可以使用更通用的跨浏览器属性?
我有一些JavaScript代码,在IE中包含以下内容:
myElement.innerText = "foo";
然而,'innerText'属性似乎在Firefox中不起作用。Firefox中有类似的吗?或者是否可以使用更通用的跨浏览器属性?
当前回答
在这里找到这个:
<!--[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));
}
在这里找到这个:
<!--[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也支持这个属性。
myElement.innerText = myElement.textContent = "foo";
编辑(感谢Mark Amery在下面的评论):只有当您确信没有代码会像jQuery那样依赖于检查这些属性是否存在时,才会这样做。但如果你正在使用jQuery,你可能只需要使用"text"函数并执行$('#myElement').text('foo'),就像其他答案显示的那样。
只是从原帖子下的评论中转发。innerHTML适用于所有浏览器。谢谢stefita。
myElement。innerHTML = "foo";