我正在尝试用这个无意义的按钮创建一个网站

    <p id="pButt" style="position:absolute; top:500px; font-family:Impact, charcoal, sans-serif">Pointless button!</p>
<button type="button" onClick="pButt()" style="position:absolute; top:550px">Don't click it</button>

<script>
function pButt() {
 var textButt = textButt + 1;
 if (textButt === 1) {
 document.getElementById("pButt").innerHTML = "Seriously, it's pointless"
 }
 else {
  if (textButt === 2) {
  document.getElementById("pButt").innerHTML = "Ouch, that tickles!"
  else {
   if (textButt >= 3) {
   document.getElementById("pButt").innerHTML = "Ok, I'm bored of writing Javascript now. No point clicking anymore!"
}
}
}
}
</script>


我希望它将ID为“ pButt”的段落中的文本第一次更改为“严重,这毫无意义”,“哦,好痒!”第二,'好吧,我现在无聊编写Javascript。再也没有点击了!”第三次。为什么代码不起作用?我对Java语言还很陌生,但是如果出现一些愚蠢的拼写错误,我真的很抱歉。

最佳答案

您必须在textButt之外声明和初始化pButt。以下将起作用:

<p id="pButt" style="position:absolute; top:500px; font-family:Impact, charcoal, sans-serif">Pointless button!</p>
<button type="button" onClick="pButt()" style="position:absolute; top:550px">Don't click it</button>

<script>
    var textButt = 0;
    function pButt() {
        textButt++;
        if (textButt === 1) {
            document.getElementById("pButt").innerHTML = "Seriously, it's pointless"
        } else if (textButt === 2) {
            document.getElementById("pButt").innerHTML = "Ouch, that tickles!"
        } else  if (textButt >= 3) {
            document.getElementById("pButt").innerHTML = "Ok, I'm bored of writing Javascript now. No point clicking anymore!"
        }
    }
</script>


或者,您可以稍微重构:

<p id="pButt" style="position:absolute; top:500px; font-family:Impact, charcoal, sans-serif">Pointless button!</p>
<button type="button" onClick="pButt()" style="position:absolute; top:550px">Don't click it</button>

<script>
    var message, textButt = 0;
    function pButt() {
        switch(++textButt) {
            case 1:
                message = "Seriously, it's pointless";
                break;
            case 2:
                message = "Ouch, that tickles!";
                break;
            default:
                message = "Ok, I'm bored of writing Javascript now. No point clicking anymore!";
        }
        document.getElementById("pButt").innerHTML = message;
    }
</script>

10-07 18:21