代码之家  ›  专栏  ›  技术社区  ›  Meep3D

用jquery匹配类

  •  1
  • Meep3D  · 技术社区  · 15 年前

    我有两个无序的列表,有点像:

    <ul class="list1">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li class="current">Item 4</li>
        <li>Item 5</li>
    </ul>
    
    <ul class="list2">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
    </ul>
    

    目标是,使用jquery,识别哪个li被标记为“current”类,然后将一个类添加到第二个列表中对应的li。我就是想不出怎么做。

    谢谢。

    4 回复  |  直到 15 年前
        1
  •  7
  •   Pointy    15 年前
    $('ul.list2 li:nth-child(' + $('ul.list1 li.current').index() + ')').addClass('current');
    

    或者你可以让它不那么恶心:

    $('ul.list2 li').eq($('ul.list1 li.current').index()).addClass('current');
    

    第二个,我更喜欢,现在我可以看到他们两个:—)这里的诀窍是:

    1. “eq”过滤器允许您基于索引从jquery列表中选择元素;
    2. “index”函数允许您 找到 相对于dom中的同级元素的索引
        2
  •  1
  •   Ali Habibzadeh    15 年前

    只要简单地使用这个:

    var initialIndex = $('.list1 .current').index();
    $('.list2 li').eq(initialIndex).addClass('current');
    
        3
  •  1
  •   David Waters    15 年前
    // Find the current item in the first list, remember its text
    var textToMatch  = $('ul.list1 li.current').text();
    // Loop through each li in the second list
    $('ul.list2 li').each(function(index, domElement){
         var curr = $(domElement);
         // if the text matchs the first then add our class
         if(textToMatch == curr.text()){
              curr.addClass('NEWCLASS');
         }
     });
    

    编辑1:这是在回答错误的问题,这个问题已经澄清了,我将把它留在这里,因为它看起来仍然很好:)

    edit2:根据flex的说法,这是一种更好的方法来实现同样的目标,而不是问题是什么。

    $('.list2 li:contains("' + // Find an li in list2 which contains
        $('.list1 li.current').text() + '")')  // the same text as the as the current li in list1
        .addClass("NEWCLASS"); // and add our new class to it
    
        4
  •  -1
  •   markcial    15 年前
    $('li.current + li').addClass('yourClass')

    编辑:对这个问题的误解

    var index = $.inArray($('li.current')[0],$('li.current').parent().children());
    $('ul:eq(1) li:eq('+index+')').addClass('selected');