JQuery Timepicker Addon - Can't create TimePic

2019-08-25 18:01发布

问题:

I have a small problem with trentrichardson's jQuery-Timepicker-Addon.

Timepicker elements created within $(document).ready() are built correctly without problems, and I can do everything from the documentation.

However, when I try to create new elements on a button's onclick JavaScript throws the error:

TypeError: $(...).timepicker is not a function

Here's my code (all the following code blocks are inside the same <script> element on the page):

$(document).ready(function () {
  $('#hora').timepicker({
      timeFormat: "hh:mm tt"
    },$.timepicker.regional['es']); //works correctly, element is generated as desired
  $('#origen_hora_confirmacion').timepicker({
      timeFormat: "hh:mm tt"
    },$.timepicker.regional['es']); //works correctly, element is generated as desired
});

Later in the same <script> element I try to run this code on a button's click event:

function agregar_vehiculo() {
  // ...
  $('#fechsalida0').timepicker({
    timeFormat: "hh:mm tt"
  }); //TypeError: $(...).timepicker is not a function
}

And on the button:

<input type="button" id="añadirVeh" name="añadirVeh" onclick="agregar_vehiculo()" value="Añadir Vehiculo">

What could be the cause of this? Is it the plugin problem or am I missing something about jQuery?

Thank you in advance

回答1:

If everything works as expected inside $(document).ready you can add the event listener from the javascript:

$(document).ready(function () {
  $('#añadirVeh').click(function () {
    $('#fechsalida0').timepicker({
      timeFormat: "hh:mm tt"
    });
  });
});

Basically re-write your agregar_vehiculo function inside of $(document).ready.