这是我的代码:
function changeText() {
document.getElementById("myHeader").innerHTML = "Have a nice day!";
document.getElementById("myButton").innerHTML = "Change that back";
document.getElementById("myButton").onclick = "changeBack()";
}
function changeBack() {
document.getElementById("myHeader").innerHTML = "Hello World!";
document.getElementById("myButton").innerHTML = "Change text";
document.getElementById("myButton").onclick = "changeText()";
}
<script src="script.js"></script>
<h1 id="myHeader">Hello World!</h1>
<button id="myButton" ; onclick="changeText()">Change text</button>
我的目标是按钮会在两个函数和文本状态之间来回切换,但所有发生的事情是它第一次切换文本然后它不再执行任何操作。我想知道如何才能正确地改变按钮所指的功能。
答案 0 :(得分:5)
简单,设置功能本身。
document.getElementById("myButton").onclick = changeText;
...
document.getElementById("myButton").onclick = changeBack;
答案 1 :(得分:4)
如果您要使用Javascript字符串而不是函数引用,则需要设置属性,而不是属性。
function changeText() {
document.getElementById("myHeader").innerHTML = "Have a nice day!";
document.getElementById("myButton").innerHTML = "Change that back";
document.getElementById("myButton").setAttribute("onclick", "changeBack()");
}
function changeBack() {
document.getElementById("myHeader").innerHTML = "Hello World!";
document.getElementById("myButton").innerHTML = "Change text";
document.getElementById("myButton").setAttribute("onclick", "changeText()");
}
&#13;
<script src="script.js"></script>
<h1 id="myHeader">Hello World!</h1>
<button id="myButton" onclick="changeText()">Change text</button>
&#13;
答案 2 :(得分:2)
您可以使用相同的评论,只需检查文字即可来回切换:
function changeText() {
var btn = document.getElementById("myButton")
var txt = document.getElementById("myHeader")
if (txt.innerHTML == 'Hello World!') {
txt.innerHTML = "Have a nice day!";
btn.innerHTML = "Change that back";
} else {
txt.innerHTML = "Hello World!";
btn.innerHTML = "Change text";
}
}
<html>
<body>
<script src="script.js"></script>
<h1 id="myHeader">Hello World!</h1>
<button id="myButton" onclick="changeText()">Change text</button>
</body>
</html>
答案 3 :(得分:2)
添加条件语句。作为一个非常天真的例子,您可以添加第三个函数并执行以下操作:
<body>
<script src="script.js"></script>
<h1 id="myHeader">Hello World!</h1>
<button id="myButton"; onclick="determineFunction()">Change text</button>
</body>
function determineFunction() {
if(document.getElementById("myHeader").innerHTML === "Have a nice day!"){
changeText();
}
else{
changeBack();
}
}
function changeText() {
document.getElementById("myHeader").innerHTML = "Have a nice day!";
document.getElementById("myButton").innerHTML = "Change that back";
document.getElementById("myButton").onclick = "changeBack()";
}
function changeBack() {
document.getElementById("myHeader").innerHTML = "Hello World!";
document.getElementById("myButton").innerHTML = "Change text";
document.getElementById("myButton").onclick = "changeText()";
}
如果您要执行此方法,则应检查所有元素的文本 - 并且可能有第三个条件,即控制台记录错误或其他内容。
这只是一种方法 - 有许多方法可以实现这一点 - 例如设置全局布尔值并检查以确定要调用的函数。