jQuery按钮超时
jQuery button with timeout
我有一个删除按钮来删除照片。第一次点击会在顶部为div
设置动画,并显示消息:"如果你真的想删除这张照片,请再次点击。"第二次点击会删除照片。如果您在第一次点击后的3秒内没有再次点击,则消息将消失。但如果它消失了,你再次点击按钮,它仍然会被删除。当消息失效时,我需要停止脚本以停止发布$.ajax()
$(".delete").toggle(function(){
$("#top").html("Click again if you really want delete this photo.");
$("#top").animate({top: "0"}).delay(3000).animate({top: "-50"});
return false;
}, function() {
$("#top").animate({top: "-50px"});
var id = $(this).attr("id");
$.ajax({
...
});
});
类似的东西(未经测试):
$(".delete").click(function()
{
if ($(this).attr('canDelete') == 'y')
{
$("#top").animate({top: "-50px"});
... do delete
}
else
{
$("#top").html("Click again if you really want delete this photo.");
$("#top").attr('canDelete', 'y')
.animate({top: "0"})
.delay(3000)
.attr('canDelete', 'n')
.animate({top: "-50"});
}
});
为什么不这样做呢?
$(".delete").click(function() {
if ( $(this).hasClass("confirm") ) {
//When the button is clicked again within 3 seconds it will have
//the confirm class and will go here
} else {
//The button will go here when clicked first time, a class
//of confirm is added for 3 seconds.
$(this).addClass("confirm");
setTimeout(function() {
$(this).removeClass("confirm");
}, 3000);
}
});
您可以在闭包中放入一个变量,如下所示:
var allowDel;
$(".delete").toggle(function(){
allowDel = true;
$("#top").html("Click again if you really want delete this photo.");
$("#top").animate({top: "0"}).delay(3000).animate({top: "-50"});
setTimeout(function() { allowDel = false; }, 3000);
return false;
}, function(){
if (!allowDel) return;
$("#top").animate({top: "-50px"});
var id = $(this).attr("id");
$.ajax({
...
});
});
另一个解决方案,这次没有任何额外的变量或属性/属性(不是说有任何显著的优势,也许有点干净)。这个使用消息DIV的Y坐标来确定是否允许删除。
演示:http://jsfiddle.net/Eu2vu/
代码:
$(".delete").click(function() {
var top = $('#top');
if (top.position().top >= 0) {
top.animate({top: "-50px"});
console.log('do delete');
}
else {
top.html("Click again if you really want delete this photo.");
top.animate({top: "0"}).delay(3000).animate({top: "-50"});
}
});
所以我编辑了它,它可以
var allowDel;
$(".delete").click(function(){
if(allowDel){
$.ajax();
allowDel = false;
}else{
allowDel = true;
setTimeout(function() {
$("#top").slideUp();
}, 3000);
return false;
}
});
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- 正在添加'X'按钮,在文本字段旁边使用javascript
- 多个单选按钮组相互干扰
- JavaScript下拉菜单-点击按钮并根据所选值重定向到url
- jQuery按钮超时
- 按钮上的if-else语句超时有效,但无法返回到原始状态
- 我的设置超时不会自动提交我的按钮
- 在导航按钮上设置 1 秒超时
- 单击按钮超时javascript
- 按钮,超时,警报未捕获类型错误:
- 表单按钮在javascript中重写超时事件
- JQuery对话框-用关闭按钮替换超时
- 如果按下按钮,我如何取消超时?
- 防止超时功能结束前点击按钮
- 扩展单击按钮时的超时功能
- 单击后退按钮并登陆带有超时重定向到同一页面的页面
- Javascript自动超时按钮动作
- 超时禁用按钮
- 为什么我的按钮在加载和超时完成后不会重定向到新的URL
- 我的按钮设置超时触发器没有加载