我有一个问题:我需要创建一个按钮来切换文本。我做到了,但是它只改变了一次(从猫到狗),但是我该如何切换,以便它会在从猫到狗,从狗到猫的变化直到单击停止按钮。
<p id="ryiaf"> CAT
<form action="script.js">
<input onclick="ryiaf.innerText = 'DOG'" type="button" value="CHANGE YOUR TEXT">
</form>
答案 0 :(得分:1)
您需要实现来回更改的逻辑。也许是这样的:
<p id="ryiaf"> CAT
<form action="script.js">
<input onclick="ryiaf.innerText = (ryiaf.innerText == 'DOG' ? 'CAT' : 'DOG')" type="button" value="CHANGE YOUR TEXT">
</form>
现在,为了提高代码的可读性,我建议在脚本文件中使用如下所示的onclick函数:
function handleClickChangeTxt() {
if (ryiaf.innerText == 'DOG') ryiaf.innerText = 'CAT';
else ryiaf.innerText = 'DOG';
}
<p id="ryiaf"> CAT
<form action="script.js">
<input onclick="handleClickChangeTxt()" type="button" value="CHANGE YOUR TEXT">
</form>
答案 1 :(得分:0)
您可以像这样通过按钮单击轻松切换/交换文本-
function toogleText() {
var x = document.getElementById("ryiaf");
if (x.innerHTML === "CAT") {
x.innerHTML = "DOG";
} else {
x.innerHTML = "CAT";
}
}
<p id="ryiaf"> CAT
<form action="script.js">
<input onclick="toogleText()" type="button" value="CHANGE YOUR TEXT"/>
</form>
演示: https://www.w3schools.com/howto/howto_js_toggle_text.asp