简体   繁体   English

如何从$ .each内部突破jQuery click事件函数

[英]How to break out from jQuery click event function from inside $.each

How can I exist from the whole jquery click event function if the condition is met inside $.each . 如果在$.each满足条件,如何从整个jquery click事件函数中存在。 One solution would be storing condition result in a variable and then have an if statement after the loop but is not there a direct way? 一种解决方案是将条件结果存储在变量中,然后在循环后使用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

 });

How to break out from jQuery click event function from inside $.each 如何从$ .each内部突破jQuery click事件函数

So you want to return false from the click handler based on the result of the inner loop. 因此,您想根据内部循环的结果从click处理程序return false You have several options: 您有几种选择:

  1. Use a simple for loop [as in your answer] 使用简单的for循环[如您的答案]

  2. Use get to get an array for the inputs, and use Array#some : 使用get获取输入的数组,并使用Array#some

     $(".main").on("click", ".button", function(e) { if ($(this).siblings('input').get().some(function(input) { return input.value == 'yourvalue'; })) { return false; } //... }); 

    which is more concise with an ES2015+ arrow function: ES2015 +箭头功能更加简洁:

     $(".main").on("click", ".button", function(e) { if ($(this).siblings('input').get().some(input => input.value == 'yourvalue')) { return false; } //... }); 
  3. Use a flag outside the loop: 在循环外使用标志:

     $(".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; } //... }); 

What you have should work. 你所拥有的应该工作。 To break a $.each loop, you simply need to return false. 要中断$ .each循环,您只需要返回false。

Returning true skips to the next iteration, equivalent to a continue in a normal loop. 返回true会跳到下一个迭代,等效于在正常循环中继续。

$(".main").on("click",".button",function(e){

    $.each(array, function(i){

       if(i === 'yourvalue') {
         return false; // will exit the $.each loop
       }

    });

 });

Converting to native loop will enable me to exist the click function when using return false 转换为本机循环将使我能够在使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM