[英]how to make the show function in an if else override the hide function permanently?
在這段代碼中我希望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>
在按鈕標記中添加一個類型按鈕:
<button type="button" onclick="myFunction()">submit</button>
為什么?
因為按鈕的默認功能是提交表單,當您單擊按鈕時表單會被提交,並且由於回發,您的元素會被隱藏,因為doc ready會再次觸發。
即使你可以用.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>
首先需要在函數體內隱藏它們。
$("#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"); } }
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.