Jquery UI datepicker不能与动态html一起工作

jquery ui datepicker not working with dynamic html

本文关键字:html 一起 工作 动态 UI datepicker 不能 Jquery      更新时间:2023-09-26

我已经成功地将jquery UI datePicker连接到一个动态创建的文本框,除了当我选择一个日期时,它不会出现在相应的文本框中,但它出现在我的第一个文本框中,这不是动态创建的。我的代码是这样的

 $(".add-more").click(function () {
        $this = $(this);
        $section = $($("." + $this.attr("data-section"))[0]).html();// This is a section in my HTML with multiple textboxes
        $this.parent().append('<div class=' + $this.attr("data-section") + '>' + $section + '</div>').fadeIn(); 
        $(".datepicker").removeClass('hasDatepicker').datepicker();
    });
HTML

<div id="Div1" class="section-container">
    <div class="education-item" style="display: none">
        <p>Institute:<input type="text" name="txtInstitute"   /></p>
        <p>Start Year:<input type="text" name="txtStartYear" class="datepicker" /></p>
        <p>End Year:<input type="text" name="txtEndYear"  class="datepicker"/></p>
    </div>
</div>
这里的

JSFiddle

尝试使用更准确的元素指示来创建日期选择器。比如这里http://jsfiddle.net/xUYM2/

$(".add-more").click(function() {
    $this = $(this);
    $section = $($("." + $this.attr("data-section"))[0]).html();
    var block = $('<div class=' + $this.attr("data-section") + '>' + $section + '</div>')
    $this.parent().append(block).fadeIn();
    block.find(".datepicker").removeClass('hasDatepicker').datepicker();
    showHideRemove($(this).parents(".section-container").find(".remove-item"), 1);
});

p。S>,最好在脚本中使用局部变量,如

    var $this = $(this); // without var keyword your variable will be global
    var $section = $($("." + $this.attr("data-section"))[0]).html();

在Add -more函数中添加这一行

$(".datepicker").removeClass('hasDatepicker').datepicker();