onchange函数被触发两次



我想将 JQuery 多日期选择器中的值用于不同的目的,但由于某种原因,当我对我得到的值进行测试时,我得到了同样的东西两次。我错过了什么吗?

我的代码 :

$('.date').datepicker({
multidate: true,
format: 'dd-mm-yyyy'
});
function printDates() {
var dates = document.getElementById("date_input").value;
console.log(dates);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js'></script>
<input type="text" name="dates" class="form-control date" id="date_input" placeholder="Pick the dates " onchange="printDates()">

使用 changeDate insstead of onchange,如下所示

$('.date').datepicker({
multidate: true,
format: 'dd-mm-yyyy'
})
.on('changeDate', function(e) {
printDates(); // `e` here contains the extra attributes
});
;
function printDates() {
var dates = document.getElementById("date_input").value;
console.log(dates);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js'></script>
<input type="text" name="dates" class="form-control date" id="date_input" placeholder="Pick the dates " >

https://bootstrap-datepicker.readthedocs.io/en/latest/events.html

使用引导日期选取器中提供的更改事件。

最新更新