单击后显示 "undefined" 的按钮
button showing "undefined" after being clicked
我有一段非常基本的代码,但在代码运行后按钮变为未定义,如何阻止它这样做?
<button id="buttonevent" onclick="partyTime()">What time is it?</button>
<script>
function partyTime() {
document.getElementById("buttonevent").innerHTML=alert("It's Party Time!");
}
</script>
alert
没有 return 任何东西,因此您将 button
的内容设置为 undefiened
。只需要 alert
代码而不设置按钮。innerHTML
.
<button id="buttonevent" onclick="partyTime()">What time is it?</button>
<script>
function partyTime() {
alert("It's Party Time!");
}
</script>
而且,由于您是新手,所以让我们从一开始就改掉坏习惯。虽然您可能会在 HTML 中看到许多使用 onclick
的代码,但您不应以这种方式设置事件。这是一项 25 年以上的技术,不会死于它应得的死亡 for so many reasons。相反,将 JavaScript 与 HTML 分开,然后在 JavaScript.
中进行事件绑定
<button id="buttonevent">What time is it?</button>
<script>
// Set up the click of the button to call the partyTime function here
// in JavaScript, not from the HTML.
document.getElementById("buttonevent").addEventListener("click", partyTime);
function partyTime() {
alert("It's Party Time!");
}
</script>
我有一段非常基本的代码,但在代码运行后按钮变为未定义,如何阻止它这样做?
<button id="buttonevent" onclick="partyTime()">What time is it?</button>
<script>
function partyTime() {
document.getElementById("buttonevent").innerHTML=alert("It's Party Time!");
}
</script>
alert
没有 return 任何东西,因此您将 button
的内容设置为 undefiened
。只需要 alert
代码而不设置按钮。innerHTML
.
<button id="buttonevent" onclick="partyTime()">What time is it?</button>
<script>
function partyTime() {
alert("It's Party Time!");
}
</script>
而且,由于您是新手,所以让我们从一开始就改掉坏习惯。虽然您可能会在 HTML 中看到许多使用 onclick
的代码,但您不应以这种方式设置事件。这是一项 25 年以上的技术,不会死于它应得的死亡 for so many reasons。相反,将 JavaScript 与 HTML 分开,然后在 JavaScript.
<button id="buttonevent">What time is it?</button>
<script>
// Set up the click of the button to call the partyTime function here
// in JavaScript, not from the HTML.
document.getElementById("buttonevent").addEventListener("click", partyTime);
function partyTime() {
alert("It's Party Time!");
}
</script>