简体   繁体   English

输入模糊后如何调用函数?

[英]How to call a function AFTER blur from input?

I'm using jquery-ui datepicker as one of my inputs. 我正在使用jquery-ui datepicker作为输入之一。 If a user blurs from an input, I display a relevant message (eg "This field is required"). 如果用户因输入内容模糊不清,则会显示一条相关消息(例如“此字段为必填”)。 For this purpose I have the following jQuery, which works perfectly fine for simple <select> and <input type="text"> tags: 为此,我有以下jQuery,它对于简单的<select><input type="text">标记非常适用:

$("input").blur(function(){
    if($(this).val()=="")
        $(this).next().text("This field is required.");
    else
        $(this).next().text("");
});

However, in case of datepicker (where I have to essentially blur to select a date) the error message gets displayed even after I've selected the date (ie selection of date is leading to the blur event). 但是,在使用日期选择器的情况下( 实际上必须 模糊选择日期), 即使选择了日期,错误消息也会显示(即选择日期会导致模糊事件)。 This requires that the .blur(function(){}); 这要求.blur(function(){}); should be called after the blur event is completed (not simultaneously). 完成后,模糊事件(非同时),应该被调用。

How to solve this situation? 如何解决这种情况?

Here's a DEMO . 这是一个DEMO

You could add your validation check to the onClose event of the datepicker, rather than the blur event of the input field: 您可以将验证检查添加到日期选择器的onClose事件,而不是输入字段的blur事件:

$("#datepicker").datepicker({onClose: function(selectedDate) {
    if(!selectedDate) {    
        $(this).next().text("This field is required.");
    }
}});

Kind of a hack, but you could just delay the check with setTimeout : 有点黑客,但您可以使用setTimeout延迟检查:

$("input").blur(function () {
    var $t = $(this);
    setTimeout(function () {
        if ($t.val() == "") $t.next().text("This field is required.");
        else $t.next().text("");
    }, 100);
});

http://jsfiddle.net/D4AGz/96/ http://jsfiddle.net/D4AGz/96/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM