防止 jQuery one() 函数上的点击跳转
我在 jQuery 中使用 one() 函数来防止多次点击。但是,当他们第二次单击该元素时,它会执行恼人的单击跳转并将您带回页面顶部。
有没有办法防止这种情况发生?取消绑定点击并在函数完成后重新绑定它具有相同的结果(并且我假设 one()
只是取消绑定事件)。
发生这种情况的一个简单示例: http://jsfiddle.net/iwasrobbed/FtbZa/
I'm using the one() function in jQuery to prevent multiple clicks. However, when they click the element a second time, it does the annoying click jump and sends you back to the top of the page.
Is there a way to prevent this from happening? Unbinding the click and re-binding it when the function is done has the same result (and I'm assuming that one()
just unbinds the event anyways).
A quick example of this happening: http://jsfiddle.net/iwasrobbed/FtbZa/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不确定这是否更好,但您可以绑定一个简单的函数来维护
返回 false
。jQuery 通过
.bind('click',false)
提供了一个快捷方式。或者如果您有多个这样的链接,一个非常有效的替代方法是使用
delegate()[docs]
方法将处理程序绑定到共同祖先,该祖先为您处理
return false;
。在这里,我只使用了
body
,但您可以使用更近的祖先。I'm not sure if this is better or not, but you could bind a simple function that maintains the
return false
.jQuery provides a shortcut for this with
.bind('click',false)
.or if you have several of these links, a very efficient alternative would be to use the
delegate()
[docs] method to bind a handler to a common ancestor that takes care of thereturn false;
for you.Here I just used the
body
, but you could use a nearer ancestor.尝试更改 href,以便不使用“#”: http://jsfiddle.net/FtbZa/1 /
Try changing the href so the '#' isn't being used: http://jsfiddle.net/FtbZa/1/
您可以使用标准的
.click()
函数和一些逻辑:.click()
< 类的someLink
的内容/a>clicked
(注意这可以是您想要的任何名称)clicked
,以便下次单击时,它将忽略您的代码。请在此处查看演示
You could use the standard
.click()
function and a little logic:someLink
for a.click()
clicked
(Note this could be any name you wanted)clicked
so next time its clicked, it will ignore your code.See the demo here
问题是,在侦听器解除绑定后,没有什么可以阻止浏览器尊重链接(将其视为锚标记)并尝试访问它。 (在这种情况下,这只会导致页面顶部。
The problem is that after the listener has been unbound there is nothing stopping the browser from honoring the link (Which it is treating as an anchor tag) and trying to go to it. (Which in this case will simply lead to the top of the page.