简体   繁体   中英

jQuery on click fires twice

Whe using jQuery .on('click', ...) the function is executed twice:

$(document).ready(function () {
    $('#collapsible-menu li a').click(function() {
        $('#collapsible-menu li').removeClass('active');
        $(this).parent('li').addClass('active');
    });
});

So what happens is that the menu item goes active for an instant and then class goes away.

I have no clue why it's being fired twice. I don't want to use event.preventDefault() or event.preventPropagation() or return false because then clicking the link will lead nowhere.

HTML:

<div class="collapse navbar-collapse" id="collapsible-menu">
  <ul class="nav navbar-nav">
    <li class="active"><a href="/expenses">Expenses</a></li>
    <li class=""><a href="/types">Types</a></li>
  </ul>
</div>

You're clicking an anchor which redirects the page to /types .

When you go to another page, whatever changes the javascript did, is lost.
So you're adding a class, then it redirects and the class is lost, the event handler doesn't fire twice
To avoid redirecting you can prevent the default action of the anchor

$('#collapsible-menu li a').click(function(e) {
    e.preventDefault();
    $('#collapsible-menu li').removeClass('active');
    $(this).parent('li').addClass('active');
});

You can not expect to keep the class, and redirect at the same time, you have to do one or the other.

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