jQuery event.preventDefault() 在第一次点击然后删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11772926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
event.preventDefault() on first click then remove
提问by ak85
I have the default anchor disabled if it has a class subnav as shown in this fiddle.
如果默认锚点具有类子导航,如本小提琴所示,我将禁用默认锚点。
I only want this disabled for the first click then I want the normal anchor functionality to be brought back. What is the best way to do this? I tried something involving the below code but this didn't seem to work?
我只希望在第一次点击时禁用此功能,然后我希望恢复正常的锚点功能。做这个的最好方式是什么?我尝试了一些涉及以下代码的东西,但这似乎不起作用?
$(this).unbind(event.preventDefault());
maybe something like this psuedo code?
也许像这个伪代码?
if (click count === 0 ) {
event.preventDefault();
}
or is there a better way to approach this?
或者有更好的方法来解决这个问题吗?
回答by Christoph
Bind the event handler with one()
docu. It executes once and automatically unbinds itself afterwards.
使用one()
docu绑定事件处理程序。它执行一次,然后自动解除绑定。
$(".subnav a").one("click", function(event) {
event.preventDefault();
});
Alternatively you can unbind it yourself directly in the function. It's good to use a namespace for that
或者,您可以直接在函数中自行解除绑定。最好为此使用命名空间
$(".subnav a").bind("click.myclick", function(event) {
event.preventDefault();
$(this).unbind(".myclick");
});
回答by The Hawk
This works well. The second click goes to the page...
这很好用。第二次点击进入页面...
$(".smallNavigation > ul > li > a").click(function (e) {
$("ul.sub-menu").hide();
$("ul.sub-menu", $(this).parent("li")).show();
e.preventDefault();
$(this).unbind(e);
}
回答by Frédéric Hamidi
You can pass false
to one():
您可以传递false
给one():
$(".subnav a").one("click", false);
Passing false
instead of a handler is equivalent to passing a handler that returns false
, effectively stopping the event's propagation and preventing its default behavior.
传递false
而不是处理程序等效于传递返回的处理程序false
,有效地停止事件的传播并防止其默认行为。
This is explained in the documentation for bind():
这在bind()的文档中进行了解释:
In jQuery 1.4.3 you can now pass in
false
in place of an event handler. This will bind an event handler equivalent to:function() { return false; }
.
在 jQuery 1.4.3 中,您现在可以传入
false
来代替事件处理程序。这将绑定一个等效于:的事件处理程序function() { return false; }
。
回答by Sujay
You could use something as simple as self unbind in the click handler.
您可以在点击处理程序中使用像 self unbind 这样简单的东西。
Something like
就像是
function stopEventOnce(event) {
event.preventDefault();
$(this).unbind('click',stopEventOnce);
return false;
}
$(".subnav a").bind('click', stopEventOnce);
回答by Pranay Rana
this will work for you
这对你有用
$("#elementid").bind("click", function( event ) {
alert("This will be displayed only once.");
event.preventDefault();
$(this).unbind( event );
});