简体   繁体   English

jQuery each() 循环在满足条件时不返回控制

[英]jQuery each() loop does not return control when a condition is met

I want return true/false from my function when the if condition is met.当满足if条件时,我想从我的 function 返回真/假。 However it's not returning true , every time it returns false .但是它没有返回true ,每次它返回false Please help me.请帮我。 Thanks.谢谢。

function catExists(cName) {
  $("#room_has_cat_table tbody tr td:first-child").each(function(index, item) {
    var existingCat = $(this).text();
    alert(existingCat);
    
    if (existingCat == cName) {
      return true;
    }
  });
  
  return false;
}

The problem with your logic is because you cannot return a value from an anonymous function.您的逻辑问题是因为您无法从匿名 function return值。

To correct your logic define a boolean variable which you can update inside the loop when a match is found:要更正您的逻辑,请定义一个 boolean 变量,您可以在找到匹配项时在循环内更新该变量:

function foo(cName) {
  let matchFound = false;

  $("#room_has_cat_table tbody tr td:first-child").each(function() {
    var existingCat = $(this).text();
    if (existingCat == cName) {
      matchFound = true;
      return; // exit the each() loop
    }
  });

  return matchFound;
}

However , a better approach entirely would be to use filter() to find the match.但是,完全更好的方法是使用filter()来查找匹配项。 This avoids the need for the explicit loop:这避免了显式循环的需要:

let matchFound = $("#room_has_cat_table tbody tr td:first-child").filter((i, el) => el.innerText.trim() === cName).length !== 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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