簡體   English   中英

遍歷列表元素-jQuery

[英]Iterating through list elements - jQuery

我有以下清單:

<ul class="my-list">
   <li>
     <ul>
      <li>Now</li> 
      <li><img src="image.png"/></li> //change this
      <li>25˚</li> //change this
     </ul>
   </li>
   <li>
     <ul>
      <li>12 AM</li>
      <li><img src="image.png"/></li>
      <li>30˚</li>
     </ul>
   </li>
</ul>

我想遍歷此列表並更改第二個“ ul”(img src,hour等)中的“ li”元素。

我做了以下jQuery代碼:

        if($(this).attr('class')=='my-list'){
            $("li").each(function(){
                $("ul").each(function(){
                    $("li:eq(0)").html("Test");
                    $("li:eq(1)").html("test2");
                    $("li:eq(2)").html("test3");
                });
            });
        }

我正在嘗試對代碼列表使用相同的代碼(這只是其中的一部分),但是我的jQuery代碼無法正常工作,我不知道為什么。 有人能幫我嗎? 謝謝。

即使您遍歷匹配的元素,也不會使用它們來縮小其子節點的范圍。 試試這個

$('.my-list ul').each(function(index, elem){
    var innerList = $(elem).children('li');
    innerList.eq(0).html('Test')
    innerList.eq(1).html('Test2')
    innerList.eq(2).html('Test3')
});

您應該使用匹配的當前ul的后代來迭代li元素,並且只針對第二個li:

if ($(this).attr('class') == 'my-list') {
    // this only target second element of 'li'
    $(this).children().eq(1).each(function () {
       // then find ul element
        $(this).find('ul').each(function () {
            // change the content by using context
            $("li:eq(0)", this).html("Test");
            $("li:eq(1)", this).html("test2");
            $("li:eq(2)",this).html("test3");
        });
    });
}

演示 - 單擊列表以查看更改

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM