空格键关闭警报

space bar dismissing alerts

本文关键字:空格键      更新时间:2023-09-26

我有一个技术问题,即如果在输入框中键入空格,它会发出"不允许有空格"的警告,然而,由于空格键也可以用来消除警告,它会立即消失在键上。警告只是闪烁然后消失,除非你按住空格键。有人能想出解决这个问题的办法吗?谢谢。

$('#email').bind('DOMAttrModified textInput input change keypress paste',function(){  
   if($(this).val().match(/['s]/g)) {
     alert("email should not contain spaces");
   } 
});   

您可以创建自己的模式,而不是使用JavaScript模式。您可以使用jQuery UI对话框,但这并不难做到。

而且,绑定到所有这些不同类型的事件可能会导致其中一些事件被不恰当地触发多次。你可以用一个简单的数据标志来检查你是否已经在警告用户的过程中。

$('#email').bind('DOMAttrModified textInput input change keypress paste', function (e) {
    var $this = $(this);
    if ($this.val().match(/['s]/g) && !$this.data('spacedout')) {
        $this.data('spacedout', true);
        $("<div>").appendTo("body").css({
            position: 'fixed',
            width: '100%',
            height: '100%',
            backgroundColor: 'black',
            opacity: '0.7',
            top: 0,
            left: 0
        }).append($("<div style='color: red;'>Spaces not allowed<br><input type=submit value=OK></div>").on('click', function () {
            $this.data('spacedout', false).trigger('focus');
            $(this).parent().remove();
        }));
        $this.trigger('blur');
    }
});
http://jsfiddle.net/ExplosionPIlls/HwYdF/

我建议使用一种不显眼的验证方法。这可以通过像colorbox这样的东西来实现(虽然这仍然有些突兀——理想情况下,如果可以的话,不要离开控件的焦点!*),并且可以像你喜欢的那样简单或复杂,而不会因为过时的模态对话框而让用户抓狂或半死。例如:

$.colorbox( html: '<p>Your message</p>', show: true );

*我一直在搜索我需要做的事情时看到noty突然出现,我渴望使用它;在此之前,我不能保证它,但可以提供像这样的

你可以试试:

document上显示警告绑定keydown之前

alert("email should not contain spaces")
$('document').keydown(function(event) {
        if (event.keyCode == 32) {
            event.preventDefault();
        }
    });

并在用户点击或键入输入时解除绑定。

我还建议使用这样的通知插件,而不是显示警报。