我是 Javascript 的新手,我尝试了下面的代码,它适用于 <div>
元素,但不适用于 <P> and <h1> elements
<script type="text/javascript">
function PrintText(){
document.getElementById('heading').innerText = 'Hello World';
}
</script>
<body>
<div id="heading"></div> // Works
<h1 id="heading"></h1> // Not Working
<P id="heading"></P> // Not Working
<button type="button" onclick="PrintText()">Submit</button>
</body>
当我使用 document.getElementById('heading').innerHTML= 'Hello World';
时对于 <P> and <h1>
元素上面的脚本有效(使用 innerHTML
而不是 innerText
)
为什么 innerText
属性不适用于 <p> and <h1>
元素?
最佳答案
第一个建议是永远不要在同一页面的多个元素上放置相同的 ID。
为什么?
因为当您执行 document.getElementById()
时,浏览器查找会在找到该 ID 的第一个元素时停止。
第二个建议是:
改变
innerText
到。
textContent
innerText
不能跨浏览器使用。最好使用标准方式将文本与 textContent
放在一起。
关于javascript - 内部文本不适用于段落和标题 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35238840/