循环访问 UL LI 以获取<a>文本值



如何循环遍历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++) { 
    }
}
您可以使用

.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>

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>

最新更新