javascript,保持按钮快速点击〜

时间:2010-12-20 07:15:32

标签: javascript

在html中,我做了一个按钮。 按钮应该每秒单击一次。 我不想允许快速按钮点击〜

所以我的代码在这里

inputTooFast = function()
{
    var curDate = new Date();
    if(curDate.getHours() == this.lastinputtime[0])
        if(curDate.getMinutes() == this.lastinputtime[1])
            if(curDate.getSeconds() == this.lastinputtime[2])
                if((curDate.getMilliseconds() - this.lastinputtime[2]) < 999)
                {
                    this.lastinputtime[0] = curDate.getHours();
                    this.lastinputtime[1] = curDate.getMinutes();
                    this.lastinputtime[2] = curDate.getSeconds();
                    this.lastinputtime[3] = curDate.getMilliseconds();
                    return true;
                }
    this.lastinputtime[0] = curDate.getHours();
    this.lastinputtime[1] = curDate.getMinutes();
    this.lastinputtime[2] = curDate.getSeconds();
    this.lastinputtime[3] = curDate.getMilliseconds();
    return false;
}

和样本用法在这里

function sendMessage()
{
    if(theObj.inputTooFast()==true)
        return;

 ...
   some valid code here
 ...

}

那么,有没有更快或更好的解决方案呢? 我正在使用jquery。

2 个答案:

答案 0 :(得分:4)

看起来您似乎没有提供用户反馈,无法单击该按钮。如果是这样,我可能会做这样的事情(live example)(如果没有,见下文):

sendMsg.blocked = 0;
function sendMsg() {
    if (sendMsg.blocked == 0) {
        ++sendMsg.blocked;
        setTimeout(removeSendMsgBlock, 1000); // If you want one second

        // ...other processing
    }
}
function removeSendMsgBlock() {
    --sendMsg.blocked;
}

如果您想向用户提供反馈(通常是个好主意),请停用此按钮(live example):

btnSendMsg = /* ...get the button element... */;
function sendMsg() {
    btnSendMsg.disabled = true;
    setTimeout(removeSendMsgBlock, 1000); // If you want one second

    // ...other processing
    display("Sending message at " + new Date());
}
function removeSendMsgBlock() {
    btnSendMsg.disabled = false;
}

更新:实际上,不需要额外的符号,只需将删除函数引用放在sendMsg函数对象上:

示例1重做:

sendMsg.blocked = 0;
function sendMsg() {
    if (sendMsg.blocked == 0) {
        ++sendMsg.blocked;
        setTimeout(sendMsg.removeBlock, 1000); // If you want one second

        // ...other processing
    }
}
sendMsg.removeBlock = function() {
    --sendMsg.blocked;
};

示例2重做:

btnSendMsg = /* ...get the button element... */;
function sendMsg() {
    btnSendMsg.disabled = true;
    setTimeout(sendMsg.removeBlock, 1000); // If you want one second

    // ...other processing
    display("Sending message at " + new Date());
}
sendMsg.removeBlock = function() {
    btnSendMsg.disabled = false;
};

答案 1 :(得分:2)

无需将这些字段存储在数组中。您可以将它们存储为Datenumber,我选择在此处执行此操作,因为您之后仅用于数字比较:

inputTooFast = function() {
    return (new Date()).getTime() - this.lastInputTime < 1000;
}

请注意,如果此操作返回false,您继续操作,则需要存储lastInputTime