我有一个“添加”按钮,可以创建一些动态文本字段。默认的开始日期和结束日期文本字段显示日期选择器。但是,动态创建的文本框未显示日期选择器。任何帮助将不胜感激。
$(document).ready(function() {
$('input[name="settings[start_date][]"]').datepicker({
maxDate: constants.MAX_YEAR + '-12-31',
changeYear: true,
changeMonth: true,
dateFormat: 'yy-mm-dd'
});
$('input[name="settings[end_date][]"]').datepicker({
maxDate: constants.MAX_YEAR + '-12-31',
changeYear: true,
changeMonth: true,
dateFormat: 'yy-mm-dd'
});
$('#container').on('click', '.remove', function() {
$(this).parent().remove();
});
$('#add').on('click', function() {
var row = $('div.addNew:first').clone();
$('#container').append(row);
});
});
<div id="container">
<div class="addNew" ?>
Start Date :
<?=form_input('settings[start_date][]', date('Y-m-d'), 'class="year-date-month-calendar input-small removetradingdates-block"')?>
End Date :
<?=form_input('settings[end_date][]', date('Y-m-d'), 'class="year-date-month-calendar input-small removetradingdates-block"')?>
<input type="button" class="remove" value="Remove" />
</div>
<input type="button" id="add" value="Add Periods" />
</div>
答案 0 :(得分:2)
您可以轻松地将日期选择器添加到新创建的元素中
在此示例中,我自由地在文本框中添加了“ datepicker”类,以使代码更简单,因此请确保同时更改HTML。通过将datepicker选项制成可重复使用的对象,我还减少了代码中的重复次数:
HTML / PHP:
<div id="container">
<div class="addNew" ?>
Start Date :
<?=form_input('settings[start_date][]', date('Y-m-d'), 'class="datepicker year-date-month-calendar input-small removetradingdates-block"')?>
End Date :
<?=form_input('settings[end_date][]', date('Y-m-d'), 'class="datepicker year-date-month-calendar input-small removetradingdates-block"')?>
<input type="button" class="remove" value="Remove" />
</div>
<input type="button" id="add" value="Add Periods" />
</div>
jQuery:
//I have assumed this, just for the sake of an example:
var constants = {
MAX_YEAR: "2020"
};
//re-usable set of options
var datePickerOptions = {
maxDate: constants.MAX_YEAR + '-12-31',
changeYear: true,
changeMonth: true,
dateFormat: 'yy-mm-dd'
};
$(document).ready(function() {
//set datepicker on all existing elements with "datepicker" class
$('.datepicker').datepicker(datePickerOptions);
$('#container').on('click', '.remove', function() {
$(this).parent().remove();
});
$('#add').on('click', function() {
var row = $('div.addNew:first').clone();
$('#container').append(row);
var pickers = row.find(".datepicker"); //find elements within the new row which have the "datepicker" class
//since we cloned them, remove the "id" attributes and "hasDatepicker" class, both of which were added by jQueryUI, otherwise the datepicker will not initialise properly on these new elements
pickers.removeAttr("id");
pickers.removeClass("hasDatepicker");
pickers.datepicker(datePickerOptions); //add a datepicker to each new element
});
});
您也可以访问http://jsfiddle.net/yqr69eca/17/来观看此代码的有效演示。
答案 1 :(得分:-1)
这样编写函数
$(document).on('click','#targetid',function(){
/*Do something logically here*/
// On a side note it will always work on dynamic,static elements
});