简体   繁体   中英

How can I break out of an each() in jQuery?

I have the following HTML + JS. I want the toggleButton to only toggle the first io-section-header. Eventually I will have multiple toggleButton's that will toggle a unique ul.

How can I achieve this?

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div><span>Section 1</span></div>
  <div class="io-section-header">
  <ul>
    <li class="advanced">Accounts</li>
    <li class="advanced">People</li>
    <li class="advanced">companies</li>
    <li class="basic">She</li>
  </ul>
   <div><span>Section 2</span></div>
   <div class="io-section-header">
    <ul>
    <li class="advanced">Accounts</li>
    <li class="advanced">People</li>
    <li class="advanced">companies</li>
    <li class="basic">P</li>
  </ul>
  </div>
  </div>

  <div class="toggleButton">Collapse</div>

<script>
    jQuery(function ($) {
        $('.toggleButton').click(function () {  
            var currentText = $(this).text();
            if(currentText === "Collapse")
                $(this).text("Expand");
            else
                $(this).text("Collapse");

            /*$('.io-section-header').each(function() {
                $("li").siblings(".advanced").toggle('fast',function(){});
            });*/

            $('.io-section-header li').siblings(".advanced").toggle('fast'); 

        });
    });
</script>

</body>
</html>

From the .each() documentation :

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

This will toggle the first advanced class in each io-section-header class

$('ul li.advanced:first', '.io-section-header').toggle('fast',function(){});

This will toggle the first advanced class in the first io-section-header class

$('ul li.advanced:first', '.io-section-header:first').toggle('fast',function(){});

return false is all you need; why aren't you using first() ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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