Disabling anchor using preventDefault() & event ordering
In my application I am using styling anchor tags in the same way as buttons. I need to be able to disable buttons, but the anchor tag does not have a disabled attribute. The way around this that I have attempted is by using preventDefault() in the anchor click event like so:
$('a.disabled').click(function (e) {
e.preventDefault();
});
This is not disabling the link. However, if I simply use the 'a' selector $('a').click(function()...
it does disable the link. I assume this is something to do with priority of events or event ordering based on the selectors.
Anyone know a way around this??
UPDATE
I have just realied that the above code works if referencing an anchors id in the selector, again this leads me to believe it is something to do with CSS selector priority, i.e. id referenced s开发者_C百科tyles override class styles etc.
I'm guessing you're setting the disabled
class AFTER you've bound the click event handler. If your element doesn't match the selector at the time of binding, it won't work. In case you want to run your handler in case your element will match your selector in the future, you need to use live().
$('a.disabled').live("click", function(e){
e.preventDefault();
});
It seems you didn't set disabled
class to anchors. Are you sure they look like
<a href="" class="disabled"></a>
?
Even if you had several events on the same link and this one wasn't the first executed preventDefault() should work anyway; as the default action is done after the whole event queue is done running.
What I think happens instead is that your event is never run; make sure that you affected the disabled class to your link
<a href="..." class="disabled"></a>
And that you don't have any of your events on it cancelling the queue during its run. Here is what you should be looking for:
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
To be 100% sure you can check that your event is running by changing your link to <a href="#" class="disabled>
(so that the page won't reload) and doing a console.log('test')
during the event. If it isn't called, it either isn't affected or has been cancelled.
精彩评论