Bootstrap Datepicker更改触发3次

Har*_*ess 21 javascript jquery datepicker twitter-bootstrap

嗨,我一直试图获得一个引导日期选择器的日期,并且能够但它似乎发射3次.注意:这不是jquery日期选择器,而是bootstrap日期选择器.

使用这个日期选择器:https://github.com/eternicode/bootstrap-datepicker,而不是旧的eyecon.ro one.

 $(".date-picker").on("change", function(e) {
      contents = $(this).val();
      id = $(this).attr('id');
      console.log("onchange contents: " + contents);
      console.log("onchange id: " + id);

 });
Run Code Online (Sandbox Code Playgroud)

HTML:

<input id="start_date" type="text" data-date-format="yyyy-mm-dd" class="date-picker form-control" />
Run Code Online (Sandbox Code Playgroud)

除了改变之外,我还使用了其他一些选项,比如

$('.date-picker').datepicker().change(function(){};
Run Code Online (Sandbox Code Playgroud)

但这并没有关闭日期选择器,希望有一个简单的解决方案.谢谢

see*_*RMS 36

您应该使用"changeDate"事件.例如:

var datePicker = $('.date-picker').datePicker().on('changeDate', function(ev) {
    //Functionality to be called whenever the date is changed
});
Run Code Online (Sandbox Code Playgroud)

有关此活动的更多信息,请查看此处的文档.

  • 这是最好最简单的方式,非常感谢你 (2认同)

pge*_*e70 8

它没有解决问题,但我正在使用datepicker通过ajax发送,所以3个更改事件导致我的问题 - 第3个事件总是失败.即使文档说要使用changeDate事件,我似乎也不应该触发输入标记的更改事件3次.价值不会改变3次!

我写了一个简单的'去抖'功能来解决这个问题.不能解决问题 - 这是由于从方法触发了多个更改事件:setValue(第508行)_setDate :(第1048行)和setValue(第508行)(版本1.3.0).

 var lastJQueryTS = 0 ;// this is a global variable.
 ....
 // in the change event handler...
    var send = true;
if (typeof(event) == 'object'){
    if (event.timeStamp - lastJQueryTS < 300){
        send = false;
    }
    lastJQueryTS = event.timeStamp;
}
if (send){
    post_values(this);
}
Run Code Online (Sandbox Code Playgroud)

它非常简单,只需找到jquery'event',并确保忽略300ms窗口中的值.在我的测试中,这一切都发生在30毫秒左右.