Jquery禁用链接5秒
我有这样的代码:
$('#page-refresh').click( function() {
$.ajax({
url: "/page1.php",
cache: false,
dataType: "html",
success: function(data) {
$('#pagelist').html(data);
}
});
return false;
});
在此代码中,是否有可能在 ajax 成功函数上禁用 #page-refresh 单击 5 秒,然后重新启用它?基本上,如果一个人单击按钮并且发生此操作,我不希望他们在另外 5 秒内再次单击并运行此操作。我查看了delay()来取消绑定点击,然后再次绑定它,但是一旦取消绑定,它就再也不允许我点击按钮了。
I have this code:
$('#page-refresh').click( function() {
$.ajax({
url: "/page1.php",
cache: false,
dataType: "html",
success: function(data) {
$('#pagelist').html(data);
}
});
return false;
});
In this code is it possible that on the ajax success function it disables the #page-refresh click for 5 seconds then re-enable it? Basically if a person clicks the button and this action happens I dont want them to click and run this action again for another 5 seconds. I looked at delay() to unbind the click for this then bind it again but once it unbinded it never allowed me to click the button anymore.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果“#page-refresh”确实是一个按钮(
button
或input type="button"
元素),您可以使用它的disabled
属性,然后设置超时来恢复它:如果它不是真正按钮,您可以模拟
disabled
属性。我将在此处使用一个类来完成此操作,以便您可以通过 CSS 向用户显示禁用状态:请注意,在第一种情况下,我保留对 DOM 元素的引用 (
varfreshButton = this;
) code>),但在第二种情况下,我保留对它周围的 jQuery 包装器的引用(var $refreshButton = $(this);
)。那只是因为 jQuery 使测试/添加/删除类名变得容易。在这两种情况下,一旦事件处理程序中的闭包被释放(在上面,即 ajax 调用完成后五秒),该引用就会被释放。您明确表示您希望在 ajax 调用完成后禁用它,但正如下面 Marcus 指出的那样,您可能希望在开始 ajax 调用时禁用它。只需将禁用位向上移动一点,并为未调用
success
的情况添加一个error
处理程序(error
处理程序通常是无论如何都是个好主意):真实按钮:
通过“禁用”类模拟:
If "#page-refresh" is really a button (a
button
orinput type="button"
element), you can use itsdisabled
property and then set a timeout to restore it:If it's not really a button, you can simulate the
disabled
property. I'll do it with a class here so you can show the disabled state for the user via CSS:Note that in the first case, I'm keeping a reference to the DOM element (
var refreshButton = this;
), but in the second case I'm keeping a reference to a jQuery wrapper around it (var $refreshButton = $(this);
). That's just because jQuery makes it easy to test/add/remove class names. In both cases, that reference is released once the closures in your event handler are released (in the above, that's five seconds after the ajax call completes).You said specifically you wanted to disable it after the ajax call is complete, but as Marcus points out below, you probably want to disable it when starting the ajax call. Just move the disabling bit up a bit, and add an
error
handler for the case wheresuccess
doesn't get called (error
handlers are usually a good idea in any case):Real button:
Simulated via 'disabled' class:
只需这样做:
Just do this:
禁用按钮 5 秒的通用解决方案:
A generic solution to disable a button for 5 seconds: