【问题标题】:Why does using .next() select all li items instead of just one为什么使用 .next() 选择所有 li 项目而不是一个
【发布时间】:2013-12-14 12:46:03
【问题描述】:

我在 ul 上使用 jQuery .next() 时遇到问题。当用户单击下一个按钮时,我将只将其添加到它旁边的li。由于某种原因,它不断将其添加到每个列表项中。这是一个工作示例:

http://jsfiddle.net/JLSR3/

$(document).ready(function(){
    $('a.next').click(function(){
        //alert('clicked');
        $('ul.menu li').next().addClass('active');
    });
});

【问题讨论】:

  • 您选择了所有列表项,然后选择了下一个列表项,这将是除第一个之外的所有列表项。你的逻辑/选择器有缺陷。
  • "...在它旁边" 在什么旁边???

标签: javascript jquery html css jquery-selectors


【解决方案1】:

这是因为$('ul.menu li') 将选择ul.menu 中的所有列表项;然后.next() 将为$('ul.menu li') 中的每个元素找到下一个元素,因此当你添加你的类时你会处理几个元素。

我认为您可能希望首先在 li 元素之一上使用活动类,然后使用类似:

$('ul.menu li.active').removeClass('active').next().addClass('active');

【讨论】:

    【解决方案2】:

    那是因为你的选择器太通用了。

    $('ul.menu li') //--> will return all li's of the menu
    .next() //--> will return all the next li's to the selected li's
    

    您可以改为将活动添加到第一个 li 开始,然后单击下一个选择 next$('ul.menu li:active') 删除当前活动的。并且对以前做同样的事情。

    你可以这样做:

    HTML:

    <ul class="menu">
        <li class="active">1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
    
    <a class="traverse" data-action="prev" href="#">previous</a>
    <a class="traverse" data-action="next" href="#">next</a>
    

    JS:

    $(document).ready(function(){
       var  $menu = $('ul.menu'), 
            $menus =  $menu.children('li');
    
        $('a.traverse').click(function(){
            var action = $(this).data('action'), //Get the action prev/next
                jump = (action === 'next' ? 'first' : 'last'), //based on action determine the jump to switch to first or last when reached the end to enable a cycle
                $active = $menus.filter('.active').removeClass('active'), //remove current active li's class
                $target = $active[action](); //get the target applying the action
    
             if ( $target.length === 0){ //If no target i.e when it is at first or last and clicking on prev or next reptly
                   $target =  $menus[jump](); //get the next element using the jump
             } 
    
            $target.addClass('active'); //add class to the target
        });
     });
    

    Demo

    【讨论】:

      【解决方案3】:

      你需要跟踪下一个元素

      var currentLi = $('.menu li').first();
      $('a.next').click(function(){   
          if(!currentLi.hasClass('active')) {
              currentLi.addClass('active');
          } else {
              currentLi.removeClass('active');
              currentLi = currentLi.next();
              currentLi.addClass('active');
          }
      });
      

      我分叉了你的 jsfiddle http://jsfiddle.net/hatemalimam/8nqxt/

      【讨论】:

        猜你喜欢
        • 2018-11-04
        • 2018-11-30
        • 1970-01-01
        • 1970-01-01
        • 2019-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-24
        相关资源
        最近更新 更多