简体   繁体   English

从回调中脱离“超级功能”

[英]Break out from a “super function” from a callback

I was wondering if it was possible to break out from a "super function" from a callback function. 我想知道是否有可能从回调函数的“超级函数”中突围而出。 I simplified my code to be more readable 我简化了代码以提高可读性

function isClicked() {
   var userInputs = $("input");
   userInputs.each(function (index, element) {
      if ($(element).val() === "")
         return; //But I want to break out from isClicked()
   });  
}

I instinctively wrote this code, but I quickly realized that my reasoning was wrong, returning only broke from the current iteration of the callback. 我本能地编写了这段代码,但是我很快意识到我的推理是错误的,返回仅从当前的回调迭代中中断。

So basically, my question is if it is possible to break out from isClicked() within the callback. 所以基本上,我的问题是,是否有可能从回调中的isClicked()中脱颖而出。

There is a easy fix to my problem, but I was wondering if the above was even possible 解决我的问题很容易,但我想知道是否甚至可以实现上述目的

Returning false stops the .each() from continuing to iterate: 返回false阻止.each()继续进行迭代:

function isClicked() {
   var userInputs = $("input");
   userInputs.each(function (index, element) {
      if ($(element).val() === "")
         return false; //Returning false ends the .each() iterating
   });
}

The code provided in the question doesn't need one, but I've sometimes needed to do something like the following with nested loops (not needed in the case provided): 问题中提供的代码不需要一个,但有时我需要对嵌套循环执行以下操作(在提供的情况下不需要):

function isClicked() {
   for (i=0;i<variable.length;i++) {
      var userInputs = $("input");
      var done = false;
      userInputs.each(function (index, element) {
         if ($(element).val() === "") {
            done = true;
            return false; //Returning false ends the .each() iterating
         }
      });
      if (done)
         return true;
   }
}

So you could do using jQuery's .eq() : 因此,您可以使用jQuery的.eq()

function isClicked() {
   var userInputs = $("input");
   for(var i=0; i<userInputs.length; i++) {
      if (userInputs.eq(i).val() === "")
         return; //But I want to break out from isClicked()
   });  
}

I don't understand why you want to break out from the main function, anyway the execution will stop, once the each loop completes. 我不明白为什么要从主函数中突围,无论如何,一旦每个循环完成,执行就会停止。

Though you can correct the code, instead of returning nothing from the each loop which continues the loop, you can return false if you want to break the loop. 尽管您可以纠正代码,但是如果您想中断循环,可以返回false,而不是从继续循环的每个循环中不返回任何内容。

($(element).val() === "") return false; ($(element).val()===“”)返回false;

function isClicked() {
   var userInputs = $("input");
   var returnval = userInputs.each(function (index, element) {
      if ($(element).val() === "")
         return false; //But I want to break out from isClicked()
   });  
   return "something"; //return something or nothing
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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