首页 > 解决方案 > 如何避免在javascript中的用户keyUp上打开多个boostrapDialog?

问题描述

我有一个页面,我在其中输入密码。密码仅由数字组成,每次用户输入字母键时,我都会显示一个 boostrapDialog。但是如果用户快速按下更多的键,多个对话框会同时打开。代码如下:

 $('#passwd', $form)
            .on('keyup', function(e){
                if(!isNumberKey(e)){
                    this.value = this.value.substr(0, this.value.length - 1);
                    BootstrapDialog.alert({message: '<%=rb.getStringForJS("ALERT_PASSWORD_NUMBER")%>', type: BootstrapDialog.TYPE_DANGER });
                }
            });
<div>
    <input class="form-control" type="password" id="passwd" name="passwd"           placeholder="CIao" maxlength="12">
</div>

有什么解决办法吗?在此先感谢,欢迎任何建议!

标签: javascripttwitter-bootstrap

解决方案


您可以添加一个变量来存储对话状态。

var isDialogOpen = false;
$('#passwd', $form)
            .on('keyup', function(e){
                //  If dialog is not opening
                if(!isNumberKey(e)  && !isDialogOpen){
                    this.value = this.value.substr(0, this.value.length - 1);
                    BootstrapDialog.alert({message: '<%=rb.getStringForJS("ALERT_PASSWORD_NUMBER")%>', type: BootstrapDialog.TYPE_DANGER });

                     // Now it is opening
                     isDialogOpen = true;
                }
            });

当您关闭对话框时,您必须更改状态。

isDialogOpen = false;

推荐阅读