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.
我有一些链接的html文件,其中大部分是我需要写在他们点击功能不是跳转到页面的顶部(e.preventDefault())ת我需要写行动除了他们实际上做的功能。
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
我问这个问题是因为我想把我的代码做得更好——但我不确定是不是这样。谢谢,阿龙
3 个解决方案
#1
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.
不,不会有任何冲突(冲突?嗯?)。您可以将额外的单击处理程序绑定到您的链接,它们将按预期工作。
#2
2
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+
需要jQuery 1.7 +
#3
1
It should work fine provided you pass the event object to the click handler. Try this
如果您将事件对象传递给单击处理程序,那么它应该工作得很好。试试这个
$('a').click(function(e){e.preventDefault()})
#1
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.
不,不会有任何冲突(冲突?嗯?)。您可以将额外的单击处理程序绑定到您的链接,它们将按预期工作。
#2
2
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+
需要jQuery 1.7 +
#3
1
It should work fine provided you pass the event object to the click handler. Try this
如果您将事件对象传递给单击处理程序,那么它应该工作得很好。试试这个
$('a').click(function(e){e.preventDefault()})