单个元素中的两个事件[Jquery]

时间:2015-11-20 12:58:08

标签: javascript jquery

(抱歉英文不好哈哈)我有一个'glyphicon-chevron-down'图标,当我点击它时,它应显示一些信息并将图标更改为'glyphicon-chevron-up',并且它工作正常。所以现在,我的span已经删除了类'down',我添加了'up'类,好吧。但我需要另一个事件,因为当用户点击'glyphicon-chevron-up'时,此事件应该与之前相反(跟随代码和页面打印):

PHP代码:

echo "<li class='folder list-group-item' id=\"".$folder['Folder']['folder_id']."\">".$space."
      <span class='glyphicon glyphicon-folder-open'></span>
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$folder['Folder']['name']."
      <a href='#'><span name='rotate' class='pull-right glyphicon glyphicon-chevron-down'>
      </span></a><br>";

JQuery代码:

$(".subfile").hide();

$(".glyphicon-chevron-down").on("click", function(){
  parents = $(this).parents('li:first');
  $(parents).siblings('li').fadeIn();
  $(this).removeClass('glyphicon-chevron-down');
  $(this).addClass('glyphicon-chevron-up');
});

$(".glyphicon-chevron-up").on("click", function(){
  parents = $(this).parents('li:first');
  $(parents).siblings('li').fadeOut();
  $(this).removeClass('glyphicon-chevron-up');
  $(this).addClass('glyphicon-chevron-down');
});

页面打印:

(The page starts this way)

(When click in the 'up' icon, should back to previous state)

如果需要更多信息,请询问评论,我会放在这里!非常感谢!

1 个答案:

答案 0 :(得分:1)

改为使用toggleClass()fadeToggle()

$(".glyphicon-chevron-down").on("click", function(){
  parents = $(this).parents('li:first');
  $(parents).siblings('li').fadeToggle(); // fadeToggle
  $(this).toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});

示例测试用例:

$(".down").on("click", function() {
  $(this).toggleClass('down up');
  $(this).siblings('p').fadeToggle();
});
.down {color: red;}
.up {color: green;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='down'>up-down</button>
<p>fade it toggle too.</p>