简体   繁体   English

jQuery:在动态创建的输入上运行多个datepicker

[英]jQuery: Running multiple datepicker's on dynamically created inputs

I am trying and failing to add datepicker to inputs that are created dynamically. 我正在尝试并且未能将datepicker添加到动态创建的输入中。

They have different id's and I am specifically targeting the new input and calling datepicker. 它们具有不同的ID,我专门针对新输入并调用datepicker。

In the jsFiddle example below it only works for the 2nd input (first one datepicker is called on) and does not work for any others after that. 在下面的jsFiddle示例中,它仅适用于第二个输入(已调用第一个datepicker),此后不再适用于其他任何输入。

Here is the jsFiddle: http://jsfiddle.net/TJfbc/1/ Press the plus sign to add more. 这是jsFiddle: http : //jsfiddle.net/TJfbc/1/按加号添加更多。

Note: I am aware the first element will not have the datepicker. 注意:我知道第一个元素将没有日期选择器。

Here's a cleaner alternative 这是一个更清洁的选择

$(function() {
    //append one handler to the parent to detect append actions
    $('.action_items').on('click', '.expand', function() {
        var $el = $(this);
        $el.parent()
            .clone()
            .appendTo($el.closest('.action_items'))
            .find('input')
            .removeClass('hasDatepicker')
            .each(function () {
                newName = this.name.slice(0,6) + (parseInt(this.name.slice(6)) + 1);
                this.name = newName;
                this.id = newName;
             })
            .datepicker();

        //change text, remove original handler, add the remove handler
        $el.text('-').off('click').on('click',function(){
            $(this).parent().remove();
        });
    })
});​

http://jsfiddle.net/TJfbc/27/ http://jsfiddle.net/TJfbc/27/

You need to "refresh" the previous textfield that has already class of 'hasDatepicker' before you can initialize a new one 您需要“刷新”具有“ hasDatepicker”类的先前文本字段,然后才能初始化新文本字段

new_action_item.find('.dpDate').removeClass('hasDatepicker').datepicker()

An improvement on readability: 可读性方面的改进:

  • No need to repeatedly call $() on new_action_item since clone() returns an already jQuery object 无需在new_action_item上重复调用$(),因为clone()返回一个已经是jQuery的对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM