昨天我正在写这个页面,我发现JQuery有一些奇怪的行为。对于下面的表单,页面的元素将正确加载结果,然后在一秒钟后刷新到其默认状态。
我还应该注意到我使用的是JQuery版本1.10.2
<form id="scoreCheck">
<p>
<label for="score">Score:</label>
<input type="text" id="score" />
</p>
<p>
<input type="button" id="validateScore" value="Check it" />
</p>
<p id="answer">The result will go here when the button is pressed.</p>
</form>和JS / JQuery函数(删除身体以节省大小)
$('#validateScore').on('click', function(){
var scoreInput = Number($("#score").val());
...
...
...
if(tempScore != scoreInput){
$("#answer").html("<p id='#result'>Invalid Score</p>");
}
else{
$("#answer").html("<p id='#result'>Valid Score</p>");
}
});这是某种错误,还是我在与按钮元素交互时错误地使用了JQuery?谢谢!
发布于 2014-01-16 05:57:42
这应能阻止这种情况的发生:
$('#validateScore').on('click', function(e){
e.preventDefault();
var scoreInput = Number($("#score").val());发布于 2014-01-16 05:55:42
这是因为如果按钮在表单中,则默认行为是submit.And,如果您指定它的类型,它的行为将像普通按钮一样。
发布于 2014-01-16 07:17:14
请参阅背后的原因,当您使用输入类型=‘type=submit’时,您要将其与输入类型='submit‘区分开来,如果是在表单内的话,则<按钮>是默认行为,现在要使用<按钮>或输入的按钮来完成这一任务,您需要防止它的默认行为,请阅读本文。
http://api.jquery.com/event.preventdefault/
https://stackoverflow.com/questions/21154254
复制相似问题