jquery toggle class on closest span

可紊 提交于 2021-01-29 07:05:53

问题


I am trying to replace a class with another class when a panel heading is clicked like so:

This currently isn't working (toggling the class) - any ideas?

jQuery:

   $('.panel-heading').click(function () {
            if ($(this).closest('span.fa').hasClass('fa-caret-down')) {
                $(this).closest('span.fa').removeClass('fa-caret-down').addClass('fa-caret-right');
            }
            else {
                $(this).closest('span.fa').removeClass('fa-caret-right').addClass('fa-caret-down');
            }

        });

HTML:

  <div class="panel-heading" data-toggle="collapse" data-parent="#accordion" data-target="#collapseOne">
     <h4 class="panel-title">
         Main <span class="fa fa-caret-down fa-lg pull-right"></span>
     </h4>
  </div>

回答1:


According to jQuery docs, we use closest to find element which is outer/upper to the element.

http://api.jquery.com/closest/

"For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree."

So in your case the span is inside the clicked element so you need to use find instead of closest.

Try this. http://jsfiddle.net/aamir/4RCMc/1/

 $('.panel-heading').click(function () {
     var $span = $(this).find('span.fa');
     if ($span.hasClass('fa-caret-down')) {
         $span.removeClass('fa-caret-down').addClass('fa-caret-right');
     } else {
         $span.removeClass('fa-caret-right').addClass('fa-caret-down');
     }
 });

Or try http://jsfiddle.net/aamir/4RCMc/3/

 $('.panel-heading').click(function () {
     $(this).find('span.fa').toggleClass( 'fa-caret-down', 'fa-caret-right' );
 });

Read more here: https://coderwall.com/p/wxjljq



来源:https://stackoverflow.com/questions/22660873/jquery-toggle-class-on-closest-span

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!