How to loop loop through a UL LI
list to get my <a>
text values?
Here's what I have tried:
<ul class="tabs">
<li><a href='#tab1'>tabOne</a></li>
<li><a href='#tab2'>tabTwo</a></li>
<li><a href='#tab3'>tabThree</a></li>
<li><a href='#tab4'>tabFour</a></li>
</ul>
function test() {
var x = $("ul.tabs li").length
alert(x)
for (i = 0; i < x i++) {
}
}
答案 0 :(得分:3)
您可以使用.each()
执行此任务:
//for each "ul.tabs a" elements
$("ul.tabs a").each(function() {
// $(this) represents to current iterated DOM element
// $(this) is "a" element selector
// If we were using a for(var i = 0;. . .) loop for arrayName[], $(this) would be arrayName[i]
console.log($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="tabs">
<li><a href='#tab1'>tabOne</a></li>
<li><a href='#tab2'>tabTwo</a></li>
<li><a href='#tab3'>tabThree</a></li>
<li><a href='#tab4'>tabFour</a></li>
</ul>
答案 1 :(得分:1)
for
循环是一个很好的方法,但要小心将jQuery方法和属性与纯JavaScript方法和属性混合。他们不认识对方的对象。
详情在演示
中发表
// This jQuery Object is like an array-like object
var lnx = $('.tabs a');
/* The .length property applies to any jQuery Object
|| Using let to define the increment variable is safe
*/
for (let i = 0; i < lnx.length; i++) {
/* Since lnx is array-like, we can use bracket
|| notation to keep track of its current index
|| on each iteration.
|| The plain JavaScript property .textContent
|| works on lnx because the brackets and
|| index number dereferrences the jQuery Object
|| into a plain JavaScript Object
*/
var txt = lnx[i].textContent;
// Log results on each iteration
console.log(txt + '\n');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="tabs">
<li><a href='#tab1'>tabOne</a></li>
<li><a href='#tab2'>tabTwo</a></li>
<li><a href='#tab3'>tabThree</a></li>
<li><a href='#tab4'>tabFour</a></li>
</ul>