<input type="text" id="text">
<span id="click">click</span>
$("#click").click(function(){
if($("#text").val().length < 1){
alert("click is empty!");
false;
}
alert("ok");
})
直播: http://jsfiddle.net/2Be8a/
为什么在这个例子中,如果 $click length == 0 我的警报点击为空(这很好)并且下一个警报正常(不好) - 为什么 false 不停止脚本? 我知道 - 我可以使用 else,但是可以用 false 停止吗?
最佳答案
需要使用关键字return
退出该函数。
$("#click").click(function(){
if($("#text").val().length < 1){
alert("click is empty!");
return false; //Exits the function
}
//This will not execute if ($("#text").val().length < 1) == true
alert("ok");
});
其他信息
- 您可能还想查看 MDN docs on
return
. 正如评论中所建议的,“最好”添加一个返回 true 的
else
。示例:$("#click").click(function(){ if($("#text").val().length < 1){ alert("click is empty!"); return false; //Exits the function } else { alert("ok"); return true; //Exits the function } });
本质上,在 jQuery 处理程序中,返回 true
与不返回任何内容相同(jQuery 将不采取任何操作)。 return false
相当于 event.stopPropagation()
。
我建议阅读jQuery Events: Stop (Mis)Using Return False更好地了解使用 return false
时实际发生的情况。
关于javascript - 如何用 false 停止脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9019431/