在这段代码中我希望show函数(正确或不正确的答案)持续但它总是恢复隐藏
$("#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>
答案 0 :(得分:1)
在按钮标记中添加一个类型按钮:
<button type="button" onclick="myFunction()">submit</button>
为什么呢?
因为按钮的默认功能是提交表单,当您单击按钮时提交表单,而 由于回发 ,您的元素会随着doc ready fires被隐藏再次。
即使您可以使用.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>
答案 1 :(得分:0)
首先需要在函数体内隐藏它们。
$("#correctOne").hide();
$("#incorrectOne").hide();
function myFunction() {
$("#correctOne").hide();
$("#incorrectOne").hide();
var inputOne = $("#inputOne").val();
if (inputOne == 10) {
$("#correctOne").show();
//confirm("Correct");
} else {
$("#incorrectOne").show();
//confirm("Incorrect");
}
}
&#13;
<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>
&#13;