在函数外部调用绑定事件

时间:2017-07-22 18:12:26

标签: javascript jquery datepicker

我正在使用KelvinLuck的jQuery datepicker插件。它非常简单明了,但我想将其绑定以进行任何更改并在控制台中显示日期。该函数在那里,但它只在初始化datePicker的函数内部有效。我想在该函数之外使用bind函数。这是一个jsFiddle

HTML

<div class="date-pick"></div>

JS

$(function() {
  $('.date-pick')
    .datePicker({
      createButton: false,
      displayClose: false,
      closeOnSelect: true,
      selectMultiple: true,
      inline: true,
      startDate: '01/01/2005',
      endDate: '31/12/2011'
    })
    .dpSetSelected(
      '18/06/2011'
    )
    .bind(
      'click',
      function() {
        $(this).dpDisplay();
        this.blur();
        return false;
      }
    )
    .bind(
      'dateSelected',
      function(e, selectedDate, $td, state) {
        console.log('You ' + (state ? '' : 'un') // wrap
          + 'selected ' + selectedDate);

      }
    )
});

当前代码成功地在控制台中显示日期,但我想在当前函数之外使用该绑定函数。所以像这样:

$('date-pick').bind(
  'dateSelected',
  function(e, selectedDate, $td, state) {
    console.log('You ' + (state ? '' : 'un') // wrap
      + 'selected ' + selectedDate);

  }
)

这可能吗?

1 个答案:

答案 0 :(得分:1)

以下是您的解决方案:

$(function() {
  $('.date-pick')
    .datePicker({
      createButton: false,
      displayClose: false,
      closeOnSelect: true,
      selectMultiple: true,
      inline: true,
      startDate: '01/01/2005',
      endDate: '31/12/2011'
    });
    // Your binding event functions have been removed from here. Its declared outside this function.
});
$('.date-pick').bind(    // You did not put `.` here
  'dateSelected',
  function(e, selectedDate, $td, state) {
    console.log('You ' + (state ? '' : 'un') // wrap
      + 'selected ' + selectedDate);

  }
);