admin管理员组

文章数量:1333724

I was wondering about that:

I have some links in my html file and to most of them I need to write in their click functions to not jump to the top of the page (which e.preventDefault() does that)ת I need to write that action aside from the functions that they actually do.

can I write something like that:

$('a').click(function(){e.preventDefault()})

Will it work? or will it create conflicts with the real functions if I will write like:

$('a').click(function(){e.preventDefault()});
$('a#goingToDoSomething').click(function(){console.log('just did it')})

I ask because I want to make my code better - but wasn't sure if that was the way.. thanks, Alon

I was wondering about that:

I have some links in my html file and to most of them I need to write in their click functions to not jump to the top of the page (which e.preventDefault() does that)ת I need to write that action aside from the functions that they actually do.

can I write something like that:

$('a').click(function(){e.preventDefault()})

Will it work? or will it create conflicts with the real functions if I will write like:

$('a').click(function(){e.preventDefault()});
$('a#goingToDoSomething').click(function(){console.log('just did it')})

I ask because I want to make my code better - but wasn't sure if that was the way.. thanks, Alon

Share Improve this question asked Dec 5, 2011 at 16:14 AlonAlon 7,75820 gold badges64 silver badges100 bronze badges 1
  • but if you have regular links to other pages or external links they will not work anymore because you disable them too! – Flo Commented Dec 5, 2011 at 16:20
Add a ment  | 

3 Answers 3

Reset to default 6

Yes it will work, if you pass the normalised event object to the callback function:

$('a').click(function (e) {
    e.preventDefault();
});

No, there won't be any conflicts (conflicts? huh?). You can bind extra click handlers to your links and they will work as expected.

The other answers are correct, but not as efficient as:

$('body').on('click', 'a', function(e){
    e.preventDefault();
});

Edit:

$(document).on

will be even faster, but not tested it, should work though

requires jQuery 1.7+

It should work fine provided you pass the event object to the click handler. Try this

$('a').click(function(e){e.preventDefault()})

本文标签: javascriptCan I write epreventDefault() using jQuery to all links in my codeStack Overflow