几个月前开始编写 javascript。我最初一直在使用“document.write()”命令,但每次使用它时都会删除我的 html 有点适得其反。
使用 getElementByID("div's ID").innerHTML = 或任何您认为更好的方法,可以有效地运行此代码,但将其添加到 div 中当前的任何内容,而不是替换它。
x = x + 1
document.write( "you have clicked this button" + x + "times")
所以就像点击 3 次后它应该说:
you have clicked this button 1 times
you have clicked this button 2 times
you have clicked this button 3 times
非常感谢。
最佳答案
element.insertAdjacentHTML('beforeend', htmlString);
其中 element
是对 DOM 元素的引用(例如从 document.getElementById
返回)。
注意:虽然 element.innerHTML += htmlString
也是可能的,但这通常是一种不好的做法,因为元素的所有 innerHTML
都会被重新解析为新的 DOM 元素,丢弃旧元素及其 append 的监听器/数据。
关于javascript - 像 document.write() 一样使用 getElementByID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22828437/