Break out from nested loop: SyntaxError: label not found

Break out from nested loop: SyntaxError: label not found

我有一个非常复杂的表单,需要对其所有元素进行验证,因此从 PHP 加载此页面已经是一个沉重的负担。

客户希望对一组字段进行验证,这样当一组至少有一行(x 个字段)填写了内容时,验证就会通过。因此,我编写了一个函数,当它找到第一行或输入的子组时我想中断它,以便它可以进入下一组验证。如果在组内找不到合适的子组,它应该 alert()。

在其他迭代中,我尝试使用 return 来摆脱困境,但它仍然继续警报。因此,阅读 SO 帖子后,我正在尝试使用标签在验证通过后立即退出。查看这些示例,似乎我正在按照其他人的建议进行操作,但我仍然收到 SyntaxError: label not found。

好的,根据 MDN 文档,它不在我认为的范围内。我已经在层次结构中上下移动了标签,但是让它太靠近嵌套函数使得它在这里对我没有用。

你会怎么做?

function checkRows(section) {
  agents = ['one', 'two', 'three', 'four','five', 'six', 'seven', 'eight'];
  loop1:
  for (var key in agents) {

     innerElements = jQuery(":input[name^=" + section + "]." + agents[key]);

     if (innerElements.length > 0) {

       var checked = [];
       jQuery.each(innerElements, function(i, element) {
         console.log("element " + element + "; length=" + element.value.length);
         if (element.value.length > 0) {
           checked.push(element);
         };
         if (checked.length == i) {
           break loop1;
      }
       });     
     }    
  }
  alert("Please enter at least one set of values for " + section);
}

http://jsfiddle.net/sam452/yj3myafq/3/

您可以尝试使用 $.each() jquery 函数

"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."

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

您也可以在 for 循环中调用 checkrows() 函数