两次调用相同的JavaScript函数timepicker

时间:2018-10-23 07:54:30

标签: javascript

我两次调用相同的javascript函数时遇到问题。当我运行代码时,第一个id =“ time”的输入域有效,但是第二个id =“ time1”的输入域则无效。

var timepicker = new TimePicker('time', {
  lang: 'en',
  theme: 'dark'
});
timepicker.on('change', function(evt) {

  var value = (evt.hour || '00') + ':' + (evt.minute || '00');
  evt.element.value = value;
});


var timepicker1 = new TimePicker('time1', {
  lang: 'en',
  theme: 'dark'
});
timepicker1.on('change', function(evt1) {

  var value1 = (evt1.hour || '00') + ':' + (evt1.minute || '00');
  evt1.element.value = value1;
});
<link href="//cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet">
<script src="//cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js">
</script>
<div>
  <input type="text" id="time" placeholder="Time">
</div>
<input type="text" id="time1" placeholder="Time">
</div>

1 个答案:

答案 0 :(得分:3)

您必须指定目标数组。 因此,您的代码如下所示:

var timepicker = new TimePicker(['time','time1'], {
  lang: 'en',
  theme: 'dark'
});
timepicker.on('change', function(evt) {
  var value = (evt.hour || '00') + ':' + (evt.minute || '00');
  evt.element.value = value;
  console.log(value);
});
<link href="//cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.css" rel="stylesheet">
<script src="//cdn.jsdelivr.net/timepicker.js/latest/timepicker.min.js">
  </script>
<input type="text" id="time" placeholder="Time">
<input type="text" id="time1" placeholder="Time">