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
3 Answers
Reset to default 6Yes 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
版权声明:本文标题:javascript - Can I write e.preventDefault() using jQuery to all links in my code? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742235460a2437996.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论