[英]How can i search ordered list using the “each” function in JQuery
I want to do this loop using jquery but I can't do it. 我想使用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; };
$.each(this.list, function(i, item){ if(this.text == item.innerHTML){ return true; } });
How can I do that using each or grep or any function else in JQuery?! 我该如何使用JQuery中的each或grep或任何其他函数来做到这一点? thanks in advance 提前致谢
You can use $.grep()
to return an array of matches, or .filter()
to return a jQuery collection of elements, where the return value of the callback should be Boolean
true
or false
您可以使用$.grep()
返回匹配数组,或使用.filter()
返回jQuery元素集合,其中回调的返回值应为Boolean
true
或false
$.grep()
$(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"; })
<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>
.filter()
$(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"); })
<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>
If you are trying to determine if a given element has .textContent
, and if true
do stuff, you can use .is()
, which returns a Boolean
; 如果您要确定给定元素是否具有.textContent
,并且如果为true
,则可以使用.is()
,它返回一个Boolean
; either true
or false
true
或false
$(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"); } })
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.