按下HTML时更改按钮的操作

时间:2015-11-09 00:39:29

标签: html

我有这个游戏的脚本:

<body>
<pre>
<p id="menuText1">Welcome To __________!</p> <!-- No name yet :P -->

<button onclick="menuButtonPressed1()" type="button" id="menuButton1">Cool, is this the whole game?</button>

<script>
function menuButtonPressed1() {
    document.getElementById("menuText1").innerHTML = "No, there's more!";
    document.getElementById("menuButton1").innerHTML = "Can I see it?";
}
</script>


</pre>
</body>

我知道如何更改按钮的标签,但如何更改按钮的实际功能?我想改变它,这样当你第二次碰到它时会出现不同的文字。

1 个答案:

答案 0 :(得分:1)

您可以使用每次按下按钮时更新的计数器全局变量。然后根据该计数器,您可以更改功能。

https://jsfiddle.net/partypete25/zug4Lsfz/6/

<script>
var counter = 0;
function menuButtonPressed1() {
    counter += 1;
    var text = document.getElementById("menuText1");
    var button = document.getElementById("menuButton1");
    if (counter==1){
     text.innerHTML = "No, there's more!";
     button.innerHTML = "Can I see it?";
    } else if (counter==2){
     text.innerHTML = "Second time text";
     button.innerHTML = "second time button label";
    }
}    
</script>