[英]How to break out from jQuery click event function from inside $.each
如果在$.each
满足条件,如何从整个jquery click事件函数中存在。 一种解决方案是将条件结果存储在变量中,然后在循环后使用if语句,但是没有直接的方法吗?
$(".main").on("click",".button",function(e){
$(this).siblings('input').each(function(){
if($(this).val() == 'yourvalue') {
return false;
}
});
//......rest of the code runs if the above condition is NOT met
});
如何从$ .each内部突破jQuery click事件函数
因此,您想根据内部循环的结果从click
处理程序return false
。 您有几种选择:
使用简单的for
循环[如您的答案]
使用get
获取输入的数组,并使用Array#some
:
$(".main").on("click", ".button", function(e) { if ($(this).siblings('input').get().some(function(input) { return input.value == 'yourvalue'; })) { return false; } //... });
ES2015 +箭头功能更加简洁:
$(".main").on("click", ".button", function(e) { if ($(this).siblings('input').get().some(input => input.value == 'yourvalue')) { return false; } //... });
在循环外使用标志:
$(".main").on("click", ".button", function(e) { var flag = false; $(this).siblings('input').each(function() { if ($(this).val() == 'yourvalue') { // can use this.value instead of $(this).val() here flag = true; return false; // Breaks the `each` loop } }); if (flag) { return false; } //... });
你所拥有的应该工作。 要中断$ .each循环,您只需要返回false。
返回true会跳到下一个迭代,等效于在正常循环中继续。
$(".main").on("click",".button",function(e){
$.each(array, function(i){
if(i === 'yourvalue') {
return false; // will exit the $.each loop
}
});
});
转换为本机循环将使我能够在使用return false
时存在click函数
$(".main").on("click",".button",function(e){
var inputs = $(this).siblings('input')
for(var x = 0; x < inputs.length; x++){
if(inputs.eq(x).val() == 'yourvalue') {
return false;
}
}
//......rest of the code runs if the above condition is NOT met
});
jQuery doc:“我们可以通过使回调函数返回false来在特定的迭代中破坏$ .each()循环。返回非false与for循环中的continue语句相同;它将立即跳至下一个迭代”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.