开发者

jQuery - Add e.preventDefault() to all links click events?

I'm making a script in jQuery, and I have many click links click events. The thing is that I don't want the links I have click events for to do anything except the event, so I put an e.preventDefault(); at start of all my click events. But I have many click events, so is there a more simple way to just add the e.preventDefault(); to all th开发者_运维知识库e links click events? Remember I also have some links that I want to work as they should, so adding the e.preventDefault(); to all the links won't work, I only want to add it to links with click event.


you can use jquery namespaced events

http://docs.jquery.com/Namespaced_Events

HTH

you can do something like this for the links you want to add a click event but prevent the default behaviour

$('a.someClass').bind('click.dontClick',function(e){

e.preventDefault();

});

and for the links you want the normal click behaviour

$('a.clickClass').bind('click.doClick',function(e){

//your event handling code here

});

DEMO


You could try overriding the bind method, or the click method, before any of your binding code runs. Here I'm overriding the click method in a fairly hacky way. I would really recommend just calling preventDefault where you need it.

(function(){
    var original = jQuery.fn.click;
    jQuery.fn.click = function(){
        // wrap your function in another function
        var f = arguments[0];
        arguments[0] = function(e) {
            e.preventDefault();
            f(e);
        }
        original.apply( this, arguments );
    }
})();

Example in action: http://jsfiddle.net/k4jzb/


This SO answer details how to detect events on an element, but it looks like the asker took that answer and built a jQuery plugin for selecting elements based on their event listeners.

So you could use that plugin and then use some event delegation like so:

$(document).delegate('a:Event(click)', 'click', function (e) { e.preventDefault(); });

Warning: I've never used this plugin myself, and I'm not really familiar with custom jQuery CSS filters, so this might not actually work. At all.


I would take @3nigma's answer a little further. Usually the links you don't want to do default actions on are like <a href="#">

So filter out these links so the page doesn't jump when clicked. I use jQuerys filter() function. Not sure if that is the best. What do you think?

$('a').filter(function(i) {
return $(this).attr("href") === "#";
})
.bind('click.dontClick',function(e){
e.preventDefault();
})

Example here: Filter a tags containing #

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜