两次点击后如何调用函数?

How to call function after two click?

我为起始日期和截止日期创建了两个日期选择器输入。

例如:

<input class="datepicker form-control" id="fromDate">
<input class="datepicker form-control" id="toDate">

和日期选择器:

<div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-front">
...
</div>

用户点击#toDate和点击#ui-datepicker-div后我想调用这个函数:

$('.icon-disable-date').hide();

我的jQuery代码是:

$('#toDate').on('click', function () {
    $('#ui-datepicker-div').on('click', function () {
        $('.icon-disable-date').hide();
    });
});

但是这个代码对我不起作用。

如果您的目标是 HTML5 支持的浏览器,这可以通过 Promises 来完成。或者您可以为不支持的浏览器添加 Promises Polyfill。

  var p1 = new Promise(function(resolve, reject){
      $('#toDate').on('click', function () {   
           resolve(true)
      })
  }).then(function(result){
    new Promise(function(resolve, reject){
       if(result) {
          $('#ui-datepicker-div').onSelect(function(){
            resolve(true)
          })
       }else {
         reject();
       }
    })
  }).then(function(result){
     if(result){
        $('.icon-disable-date').hide();
     }
  });

正如@KevinB 在评论中所讨论的那样,如果您希望图标在两个日期都被选中时消失,您可以使用输入的更改事件更轻松地做到这一点:

$('.datepicker').datepicker();
$('.datepicker').change(function() {
    if ($('#fromDate').val() != "" && $('#toDate').val() != "") {
        $('.icon-disable-date').hide();
    }
});

这与顺序无关,即使用户键入日期而不是选择日期也是如此。

JSFiddle:http://jsfiddle.net/tycugh4t/

您也可以使用日期选择器 onChange 事件来执行此操作,但它不会捕获用户在输入字段中键入的情况:

$('.datepicker').datepicker({
  onSelect: function() {
    if ($('#fromDate').val() != "" && $('#toDate').val() != "") {
      $('.icon-disable-date').hide();
    }
  }
});