【问题标题】:Return false won't stop loop with value of 1返回 false 不会停止值为 1 的循环
【发布时间】:2026-01-01 22:15:01
【问题描述】:

我有一个循环遍历动态表格的函数,查找突出显示的单元格。

在以下代码中,两个警报都会触发。当“previous”为 1 时,循环应该在“return false”处停止。

如何停止循环?

for (i = 2; i < 5; i++) {
    $("#tablegrid").find("td:nth-child("+i+")").each(function() {
       if ($(this).hasClass("highlighted")) {
         var previous = i-1;

         if (previous===1) {
           alert("loop should now stop");
           return false;
         }

         alert("loop has continued");
       }
     });
}

【问题讨论】:

  • 你想跳出哪个循环?您正在打破使用each 创建的循环;如果你想打破外部for 循环,你需要设置一个标志。
  • 谢谢。好点子。能够根据此建议修复它。我只是在每个循环中设置了一个标志,如果存在该标志,我将关闭 for 循环。谢谢。
  • @user749798 如果这解决了你的代码问题,你应该分享你的解决方案以供将来参考,如果人们碰巧遇到这个试图解决类似的问题。

标签: javascript jquery loops return each


【解决方案1】:

for 循环内使用break;,在each 循环内使用return false; 以在中间停止。

for (i = 0; i < 10; i++) {
   if (i===5) {
      alert("loop should now stop");
      nextFunction();
      break;
   }         
   alert("loop has continued");
}

function nextFunction(){
    alert("Next Function");
    $('.box').each(function(){
        if($(this).index() == 4){
         alert("loop should now stop");
         anotherFunction();
         return false; 
         
        }
          alert("each has continued");
    })
    
}

function anotherFunction(){
 alert("another function");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

【讨论】: