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

2019-04-17 22:21发布

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?

5条回答
Melony?
2楼-- · 2019-04-17 23:08
return(false);

should do it.

查看更多
你好瞎i
3楼-- · 2019-04-17 23:13

Use return false; between each loop.

查看更多
▲ chillily
4楼-- · 2019-04-17 23:21

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

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/

查看更多
别忘想泡老子
5楼-- · 2019-04-17 23:24

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

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

查看更多
戒情不戒烟
6楼-- · 2019-04-17 23:25

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

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.

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

查看更多
登录 后发表回答