[英]jQuery on click fires twice
Whe using jQuery .on('click', ...)
the function is executed twice: 使用jQuery .on('click', ...)
该函数执行两次:
$(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. 我不想使用event.preventDefault()
或event.preventPropagation()
或return false
因为单击链接将无济于事。
HTML: 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
. 您正在单击将页面重定向到/types
的锚点。
When you go to another page, whatever changes the javascript did, is lost. 当您转到另一个页面时,JavaScript所做的任何更改都将丢失。
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. 您不能期望保留该类并同时进行重定向,而必须要做一个或另一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.