jQuery .load() 如何防止双击双重加载
我正在使用 jQuery load() 函数将一些页面加载到容器中。这是代码:
$('div.next a').live('click',function() {
$('.content').load('page/3/ #info','',function(){
//do something
});
return false;
});
一切工作正常,但问题是当我快速双击 div.next 链接时,从控制台我看到它加载页面两次,因为我快速双击了。我什至可以单击 3 次,它将加载 3 次并在控制台中显示,如下所示:
GET http://site/page/3/ 200 OK 270ms
GET http://site/page/3/ 200 OK 260ms
我的问题是如何防止此类双击,并且无论单击多少次,都不让加载目标页面一次以上。
谢谢。
I am using jQuery load() function to load some pages into container. Here is the code:
$('div.next a').live('click',function() {
$('.content').load('page/3/ #info','',function(){
//do something
});
return false;
});
Everything works just fine but the problem is when I quickly double click the div.next link, from console I see that it loads the page twice because I did a quick double click. I could even make it 3 clicks and it will load it 3 times and show in console smth like that:
GET http://site/page/3/ 200 OK 270ms
GET http://site/page/3/ 200 OK 260ms
My question is how to prevent such double clicking and not to let load the target page more then once no matter how many times it was clicked.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
优秀的 JavaScript 发生了什么?为什么你们都想用纯 jQuery 来解决这个问题?
附带说明一下,永远不要永远不要使用
.live()
。使用 .delegate 代替,例如:为什么? Paul Irish 解释道:http://paulirish.com/2010/on-jquery-live/
回答您的评论...
如果您将委托函数嵌套在 AJAX 调用中(
.load()
、.get()
等),则可能会发生这种情况。div.next
必须位于页面上才能正常工作。如果div.next
不在页面上,并且它不是嵌套的,只需执行以下操作:http://api.jquery.com/delegate/
委托需要选择器作为动态添加元素的父元素。然后,委托的第一个参数(上一个示例中的
div.next a
)是要在所选元素 (#wrapper
) 中查找的元素。如果包装器未包装在任何元素中,则包装器也可以是body
。Whatever happened to good ol' JavaScript? Why are you all trying to figure it out with pure jQuery?
As a side note, never never never use
.live()
. Use .delegate instead like:Why? Paul Irish explains: http://paulirish.com/2010/on-jquery-live/
To answer your comment...
This could happen if you have your delegate function nested inside your AJAX call (
.load()
,.get()
, etc). Thediv.next
has to be on the page for this to work. Ifdiv.next
isn't on the page, and this isn't nested, just do this:http://api.jquery.com/delegate/
Delegate needs the selector to be the parent of the dynamically added element. Then, the first parameter of delegate (
div.next a
in the last example) is the element to look for within the selected element (#wrapper
). The wrapper could also bebody
if it's not wrapped in any element.您可以尝试使用 jquery one 方法:
You could try using the jquery one method:
您可以使用
die()
取消绑定click
事件:或者您可以在单击元素后为其指定
.clicked
类:并检查是否执行逻辑时该类存在:
You could unbind the
click
event withdie()
:Or you could give the element a
.clicked
class once it is clicked:And check if that class exists when performing your logic:
将您是否正在等待加载存储在变量中。
Store whether you're waiting for the load in a variable.