在下面的代码中,为什么标题文本会在页面加载时发生变化,而不是仅在单击按钮后发生变化?
<h1 id="header">This is a header</h1>
<button id="btn1">Change text</button>
<script>
function change_text(target_id, target_text) {
document.getElementById(target_id).textContent = target_text;
}
button1 = document.getElementById("btn1")
button1.onclick = change_text("header", "something")
</script>
最佳答案
如果您想重用该函数并将 onclick 保留在标记之外,您可以这样做:
<h1 id="header">This is a header</h1>
<button id="btn1">Change text</button>
<script>
function change_text(target_id, target_text) {
document.getElementById(target_id).textContent = target_text;
}
button1 = document.getElementById("btn1")
button1.onclick = function () {
change_text("header", "something");
}
</script>
这使用了一种称为匿名函数
的东西。
在此了解更多信息:JavaScript Functions
关于javascript - 脚本不等待 onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49181119/