在动态创建的字段上使用JQuery Datepicker [英] Use JQuery Datepicker on dynamically created fields
问题描述
我必须在wordpress站点中使用datepicker,在该站点中,一个插件会动态创建具有相同名称(数组),相同#id和相同.class的字段,我尝试使用focus来使用它,但是却出现了错误
I have to use datepicker in wordpress site, in which a plugin creates fields dynamically with same name(array), same #id and same .class i try to use it using focus but i got error on it
TypeError: inst is undefined
请帮助
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="assests/jquery-ui.min.css" rel="stylesheet">
<script src="assests/jquery.js"></script>
<script src="assests/jquery-ui.js"></script>
</head>
<body>
<div class="mytemplate" style="display: none;">
<input id="datepicker" type="text" name="name[]">
</div>
<div class="dates">
<div>
<input id="datepicker" type="text" name="name[]">
</div>
</div>
<input type="button" value="Add more" onclick="myfunction()">
<script>
function myfunction() {
$(".mytemplate").clone().removeClass("mytemplate").show().appendTo(".dates");
}
</script>
<script>
$(document).on("focus", "#datepicker", function(){
$(this).datepicker();
});
</script>
</body>
</html>
推荐答案
对于所有日期选择器输入,您都有id="datepicker"
,但是ID在给定的DOM中应该是唯一的.使用class="datepicker"
代替.而且,由于无论如何都在使用jquery,因此不需要使用普通的javascript onclick
函数.
you have id="datepicker"
for all your datepicker inputs, but ids are supposed to be unique in a given DOM. use class="datepicker"
instead. and also, since you're using jquery anyways, you dont need to use vanilla javascript onclick
function.
演示: http://jsfiddle.net/swm53ran/331/
<div class="mytemplate" style="display: none;">
<input class="datepicker" type="text" name="name[]"/>
</div>
<div class="dates">
<div>
<input class="datepicker" type="text" name="name[]"/>
</div>
</div>
<input type="button" class="addmore" value="Add more">
$(document).ready(function() {
$('.addmore').on('click', function() {
$(".mytemplate").clone().removeClass("mytemplate").show().appendTo(".dates");
});
$(document).on("focus", ".datepicker", function(){
$(this).datepicker();
});
});
这篇关于在动态创建的字段上使用JQuery Datepicker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!