问题描述
|
在我的应用程序中,我以与按钮相同的方式使用样式锚标签。我需要能够禁用按钮,但是锚标记没有禁用的属性。我尝试解决此问题的方法是在锚点单击事件中使用preventDefault(),如下所示:
$(\'a.disabled\').click(function (e) {
e.preventDefault();
});
这不是禁用链接。但是,如果我只是使用\'a \'选择器$(\'a\').click(function()...
,它将禁用链接。我认为这与事件优先级或基于选择器的事件排序有关。
有人知道解决这个问题的方法吗?
更新
我刚刚意识到上面的代码可以在选择器中引用锚点ID的情况下工作,再次使我相信这与CSS选择器优先级有关,即ID引用的样式覆盖类样式等。
解决方法
我猜想您是在绑定click事件处理程序之后设置
disabled
类。如果绑定时您的元素与选择器不匹配,则它将不起作用。如果您想运行处理程序以防将来您的元素与选择器匹配,则需要使用live()。
$(\'a.disabled\').live(\"click\",function(e){
e.preventDefault();
});
, 似乎您没有将disabled
类设置为锚。你确定他们看起来像
<a href=\"\" class=\"disabled\"></a>
?
, 即使您在同一链接上有多个事件,而这个事件不是第一个执行的preventDefault()仍然可以工作;因为默认操作是在整个事件队列运行完毕后完成的。
我认为发生的事情是您的活动永远不会运行。确保您影响了禁用类的链接
<a href=\"...\" class=\"disabled\"></a>
而且您没有任何事件可以在队列运行期间取消队列。这是您应该寻找的:
event.stopPropagation() // stop event bubbling,prevent the event to apply on his parent eg if your <a> is in a div,prevent the div click event queue to run -- SHOULDN\'T BE YOUR PROBLEM
event.stopImmediatePropagation() // same as stopPropagation() and in addition stop the event queue on this element (so if you have 3 clicks event on your link and the first calls this,the other two won\'t run)
return false; // fully cancel the event,has the effect to also stop the event queue,similar to calling preventDefault() AND stopImmediatePropagation() -- SHOULDN\'T BE YOUR PROBLEM
要100%确保您可以通过将链接更改为<a href=\"#\" class=\"disabled>
(以便页面不会重新加载)并在活动期间进行console.log(\'test\')
来检查事件是否正在运行。如果未调用,则它不受影响或已被取消。