jQuery 如何动态退出jquery $.each()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2973333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:38:15  来源:igfitidea点击:

how to dynamically exit a jquery $.each()?

jqueryloopseach

提问by peter

i have a list of images which i am getting through ajax and then using jquery $.each() i loop through the images and display a image one after the other after an interval of one second. I want the user to be able click on a stop button and so that the user can stop at a particular image if he wants to. So i need to dynamically exit $.each() when the user clicks on the stop button. Is it possible to do it?

我有一个图像列表,我通过 ajax 获取这些图像,然后使用 jquery $.each() 我循环浏览图像并在一秒的间隔后一个接一个地显示图像。我希望用户能够单击停止按钮,以便用户可以根据需要在特定图像处停止。所以我需要在用户点击停止按钮时动态退出 $.each()。有可能做到吗?

回答by Adeel

You can use return falseto break out of each()loops early.

您可以使用return falseeach()提前跳出循环。

Example:

例子:

<script>
    $("button").click(function () {
      $("div").each(function (index, domEle) {
        // domEle == this
        $(domEle).css("backgroundColor", "yellow"); 
        if ($(this).is("#stop")) {
          $("span").text("Stopped at div index #" + index);
          return false;
        }
      });
    });

</script>

Source: http://api.jquery.com/each/

来源http: //api.jquery.com/each/

回答by user113716

To break out of an each()loop you would:

要跳出each()循环,您将:

return false;

So your button could set a variable when clicked that the each loop checks each pass, then returns false when the variable is set.

因此,您的按钮可以在单击时设置一个变量,每个循环都会检查每个传递,然后在设置变量时返回 false。

http://api.jquery.com/each/

http://api.jquery.com/each/

回答by Anpher

http://api.jquery.com/each/

http://api.jquery.com/each/

We can stop the loop from within the callback function by returning false.

我们可以通过返回 false 从回调函数中停止循环。

回答by jAndy

return(false);

should do it.

应该这样做。

回答by Rifky

Use return false;between each loop.

return false;在每个循环之间使用。