问题
I'm struggling with the following problem: I dynamically create input elements and I try to attach a datepicker to it. But it works only when I click somewhere outside the input element and then on the input again. Console log is working fine on first click, so I don't know what is the issue here?
$(document).ready(function(){
$("div.single_condition").on("click", "input", function(){
if($("select.select_operator").val() == '>'){
console.log("O.K.");
$(this).datepicker();
}
else {
console.log("NOT O.K.");
}
});
});
回答1:
Even if you bind a datepicker to your input correctly using .datepicker()
, you need to show it on first click.
Try this code,
$(this).datepicker().datepicker("show");
Demo
Changed JS :
$("div.single_condition").on("click", "input", function () {
if ($("select.select_operator").val() == '>') {
console.log("O.K.");
$(this).datepicker().datepicker("show");
} else {
console.log("NOT O.K.");
}
});
Suggestion : Bind the .datepicker()
after you append the dynamic elements instead of on click
.
来源:https://stackoverflow.com/questions/24487664/jquery-on-click-doesnt-work-on-first-click-with-a-dynamic-element