This question already has an answer here:
这个问题在这里已有答案:
- jQuery: how do I loop through all 'a' elements? 5 answers
- jQuery:如何遍历所有'a'元素? 5个答案
I have html:
我有html:
<ul class="lorem">
<li>text</li>
<li>text</li>
<li>hello</li>
<li>text</li>
</ul>
How do I loop through this using jQuery? Something like:
我如何使用jQuery循环这个?就像是:
var listItem = nums.getElementsByTagName(".lorem li");
for (var i=0; i < listItem.length; i++) {
// if current loop has text 'hello' do something
if ($(this).text() == 'hello') {
// do something
}
}
2 个解决方案
#1
4
In jQuery you'd use each()
:
在jQuery中你会使用each():
$('.lorem li').each(function() {
if ($(this).text() == 'hello') {
console.log('hello found');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="lorem">
<li>text</li>
<li>text</li>
<li>hello</li>
<li>text</li>
</ul>
Alternatively you could filter()
the elements to find the one with the matching text without using an explicit loop:
或者,您可以使用filter()元素来查找具有匹配文本的元素,而无需使用显式循环:
var $li = $('.lorem li').filter(function() { return $(this).text() == 'hello'; });
$li.css('color', '#C00');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="lorem">
<li>text</li>
<li>text</li>
<li>hello</li>
<li>text</li>
</ul>
#2
0
$(".lorem li").each(function(){
if ($(this).text() == 'hello') {
alert($(this).text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="lorem">
<li>text</li>
<li>text</li>
<li>hello</li>
<li>text</li>
</ul>
#1
4
In jQuery you'd use each()
:
在jQuery中你会使用each():
$('.lorem li').each(function() {
if ($(this).text() == 'hello') {
console.log('hello found');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="lorem">
<li>text</li>
<li>text</li>
<li>hello</li>
<li>text</li>
</ul>
Alternatively you could filter()
the elements to find the one with the matching text without using an explicit loop:
或者,您可以使用filter()元素来查找具有匹配文本的元素,而无需使用显式循环:
var $li = $('.lorem li').filter(function() { return $(this).text() == 'hello'; });
$li.css('color', '#C00');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="lorem">
<li>text</li>
<li>text</li>
<li>hello</li>
<li>text</li>
</ul>
#2
0
$(".lorem li").each(function(){
if ($(this).text() == 'hello') {
alert($(this).text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="lorem">
<li>text</li>
<li>text</li>
<li>hello</li>
<li>text</li>
</ul>