简体   繁体   中英

Changing bootstrap glyphicon onclick function

I'm trying to swap .glyphicon-menu-down to glyphicon-menu-up when user click on the link. What am I doing wrong? It's not working. Am I miss-using jquery?

Markup

  <a data-toggle="collapse" data-parent="#accordion" href="#collapse1">
              Admin
                <span class="panelarrow glyphicon glyphicon-menu-down pull-right"></span></a>

Script

    $(document).ready(function(){
$('.panelarrow').click(function(){
    $(this).find('span').toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
});
    });

In your case $(this) refers to .panelarrow and you are trying to find span element inside that .panelarrow .

Solution:

$(document).ready(function() {
  $('.panelarrow').click(function(){
    $(this).toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
  });
});

Or if you want to change your icon by clicking on the a element use this:

$(document).ready(function() {
  $('[data-toggle="collapse"]').click(function(){
    $(this).find('span').toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up');
  });
});

Clicking on the span (which includes the glyphicon) will let you use "this" to refer to the span - then the toggle classes can be included in the one command:

$(document).ready(function(){
  $('.panelarrow').click(function(){
    $(this).toggleClass('glyphicon-menu-down glyphicon-menu-up');
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM