gpt4 book ai didi

javascript - 如何使 if else 中的显示功能永久覆盖隐藏功能?

转载 作者:搜寻专家 更新时间:2023-10-31 08:51:43 24 4
gpt4 key购买 nike

在这段代码中,我希望显示功能(正确或不正确的答案)持续存在,但它总是恢复为隐藏

$("#correctOne").hide();
$("#incorrectOne").hide();

function myFunction() {
var inputOne = $("#inputOne").val();
if (inputOne == 10) {
$("#correctOne").show();
//confirm("Correct");
} else {
$("#incorrectOne").show();
//confirm("Incorrect");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>What number am I thinking of?</h1>
<p>Divide me by four and my remainder is two. I am net if you see me through the looking glass.</p>
<form>
<input id="inputOne" type="text" placeholder="Answer Here">

<button onclick="myFunction()">submit</button>
</form>
<h2 id="correctOne">Yes!</h2>
<h3 id="incorrectOne">Nope!</h3>

最佳答案

在按钮标记中为按钮添加类型:

<button type="button" onclick="myFunction()">submit</button>

为什么?

因为按钮的默认功能是提交表单,当您单击该按钮时您的表单会被提交,并且由于回发您的元素在文档就绪触发时被隐藏再次。

  1. 点击按钮。
  2. 调用函数并执行代码。
  3. 提交表单。
  4. 回发发生页面再次重新加载。
  5. 再次隐藏元素会被触发。

甚至你可以用 .toggle(boolean) 来简化它:

$("#correctOne").hide();
$("#incorrectOne").hide();

function myFunction() {
var inputOne = $("#inputOne").val();

$("#correctOne").toggle(inputOne == 10); // .toggle(true) to show
$("#incorrectOne").toggle(inputOne != 10); // .toggle(false) to hide

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>What number am I thinking of?</h1>
<p>Divide me by four and my remainder is two. I am net if you see me through the looking glass.</p>
<form>
<input id="inputOne" type="text" placeholder="Answer Here">

<button type="button" onclick="myFunction()">submit</button>
</form>
<h2 id="correctOne">Yes!</h2>
<h3 id="incorrectOne">Nope!</h3>

关于javascript - 如何使 if else 中的显示功能永久覆盖隐藏功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41520042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com