如何循环遍历UL LI
列表以获取我的<a>
文本值?
这是我尝试过的:
<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++) {
}
}
最佳答案
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>