jQuery目标next()html项目

时间:2016-09-12 23:35:06

标签: javascript jquery html

嗨我有一个像这样生成的项目列表:

    <li class="panel-title">Item 1<i class="fa pull-right fa-plus"></i></li>
    <ul class="panel-body">...</ul>
    <li class="panel-title">Item 2<i class="fa pull-right fa-plus"></i></li>
    <ul class="panel-body">...</ul>
    <li class="panel-title">Item 3<i class="fa pull-right fa-plus"></i></li>
    <ul class="panel-body">...</ul>

点击'li'项后,我只需要下一个'ul'即可展开。不确定如何解决这个问题next()是否是正确的行动 继承我的代码

  $('li.panel-title > .fa').on("click",function() {
  var $currIcon = $(this); 
  var $contents = $('ul.panel-body');         
  if($currIcon.hasClass('fa-plus')) {   

          $currIcon.$contents.next().slideDown();             
          $currIcon.removeClass('fa-plus');
          $currIcon.addClass('fa-minus');             
  } else if($currIcon.hasClass('fa-minus')) {             
          $currIcon.$contents.next().slideUp();                   
          $currIcon.removeClass('fa-minus');
          $currIcon.addClass('fa-plus');
  }  
 });

2 个答案:

答案 0 :(得分:1)

试试这个

$('li.panel-title > .fa').on("click",function() {
  var $currIcon = $(this); 
  var $contents = $('ul.panel-body');         
  if($currIcon.hasClass('fa-plus')) {
          $currIcon.parent().next().slideDown();             
          $currIcon.removeClass('fa-plus');
          $currIcon.addClass('fa-minus');             
  } else if($currIcon.hasClass('fa-minus')) {             
          $currIcon.parent().next().slideUp();                   
          $currIcon.removeClass('fa-minus');
          $currIcon.addClass('fa-plus');
  }  
 });

答案 1 :(得分:0)

以下是jQuery代码:

$('li.panel-title > .fa').on("click", function() {
    var $currIcon = $(this);
    var $contents = $($(this).closest('li').next().children('ul'));

    if ($currIcon.hasClass('fa-plus')) {
        $contents.slideDown();
        $currIcon.removeClass('fa-plus');
        $currIcon.addClass('fa-minus');
    } else if ($currIcon.hasClass('fa-minus')) {
        $contents.slideUp();
        $currIcon.removeClass('fa-minus');
        $currIcon.addClass('fa-plus');
    }
});

我附加了一个codepen。我稍微修改了HTML标记,因为ul直接位于其父节点ul之下。

http://codepen.io/wooljs/pen/pEgbkB