【发布时间】:2012-07-23 16:30:38
【问题描述】:
假设我有以下代码:
<html>
<head></head>
<body>
<div id="d">some text</div>
<script type="text/javascript">
var d = document.getElementByid('d');
var innerText = d.innerText || d.textContent;
innerText = 'new text';
</script>
</body>
</html>
我想更改 id='d' 的 div 标签的文本值。不幸的是,上面的代码块不起作用,文本内容也没有改变。
如果执行以下配方,它会起作用:
if (d.innerText) d.innerText = 'new text';
else d.textContent = 'new text';
但我不喜欢上面的食谱,因为它不紧凑。
你有什么建议为什么第一种方法不起作用?
【问题讨论】:
-
为什么不将第二种解决方案放入一个函数中,其中一个参数用于元素,一个参数用于字符串。然后你只需要做
setText(mydiv, "new text"); -
不是
document.getElementByid应该是document.getElementByIdIid应该大写。 -
d[('innerText' in d) ? 'innerText' : 'textContent' ] = 'New text';
标签: javascript html cross-browser innertext