如何使用"每个"来搜索有序列表? JQuery中的函数

时间:2017-03-03 17:30:57

标签: javascript jquery

我想使用jquery做这个循环,但我不能这样做。

这是我的代码



this.isFound = function (li, text){
  for(var i = 0; i<li.length; i++){
    if(li[i].innerHTML == text){
      this.showError("Sorry, You can't enter a string twice");
      return true;
      break;
    }
  }
  return false;
};
&#13;
&#13;
&#13;

这是我的JQuery循环

&#13;
&#13;
$.each(this.list, function(i, item){
  if(this.text == item.innerHTML){
    return true;
  }
});
&#13;
&#13;
&#13;

如何使用JQuery中的每个或grep或其他任何函数来执行此操作? 提前谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用$.grep()返回匹配数组,或.filter()返回jQuery元素集合,其中回调的返回值应为Boolean {{1} }或true

false

&#13;
&#13;
$.grep()
&#13;
$(function() {
  var text = "abc";
  var res = $.grep($("li"), function(el, index) {
    return el.textContent === text
  });
  // `res` is an array containing one or more `DOM` elements
  console.log(res);
  res[0].style.color = "red";
})
&#13;
&#13;
&#13;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <ul> <li>abc</li> <li>def</li> <li>ghi</li> </ul>

&#13;
&#13;
.filter()
&#13;
$(function() {
  var text = "def";
  var res = $("li").filter(function(index, el) {
    return el.textContent === text
  });
  // `res` is a jQuery object containing one or more `DOM` elements
  // where jQuery methods can be chained
  console.log(res);
  res.css("color", "green");
})
&#13;
&#13;
&#13;

如果您要确定某个元素是否包含<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <ul> <li>abc</li> <li>def</li> <li>ghi</li> </ul>,以及.textContent是否有效,则可以使用true,它会返回.is(); Booleantrue

&#13;
&#13;
false
&#13;
$(function() {
  var text = "ghi";
  var i = 0;
  var res = $("li").is(function(index, el) {
    i = index;
    return el.textContent === text
  });
  // `res` is a `Boolean`
  console.log(res);
  if (res) {
    alert(text + " has already been set");
    $("li").eq(i).css("color", "gold");
  }
})
&#13;
&#13;
&#13;