【问题标题】:jquery ui datepicker not working with dynamic htmljquery ui datepicker不适用于动态html
【发布时间】:2014-03-15 10:48:52
【问题描述】:

我已成功将 jquery UI datePicker 附加到动态创建的文本框,Al 工作正常,除非我选择的日期没有出现在相应的文本框中,但它出现在我的第一个不是动态创建的文本框中。我的代码是这样的

 $(".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 Here

【问题讨论】:

  • 试试jsfiddle.net/xUYM2(我只是使用更准确的元素指示来创建日期选择器)
  • 啊哈..这就像一个魅力。你可以在这里添加这个作为答案:)

标签: javascript jquery html jquery-ui datepicker


【解决方案1】:

尝试使用更准确的元素指示来创建日期选择器。喜欢这里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();

【讨论】:

  • 我现在在你的代码中发现了一些问题,比如如果我删除了第一个 html 中的 display:none 部分,我就无法在那里初始化 datepicker。在这里摆弄jsfiddle.net/xUYM2/1
  • 你能看看那个
  • @Athul 在脚本开始处添加这一行,$(".datepicker").removeClass('hasDatepicker').datepicker();演示:jsfiddle.net/xUYM2/2
  • 哦,对不起。那是因为我删除了 $(".datepicker").datepicker();来自 ini 函数。但是你会遇到问题。因为 datepicker 将 id 添加到他系带的元素(如 dp1394890273025 ) - 以识别输入。如果您将创建 datepicker 对象然后复制 html 块 - 您也将复制元素 id。您将获得两个具有相似 id 的元素(在我的情况下为 dp1394890273025)。所以 - 这是无效的 html 并且按 id 搜索将不起作用。这就是为什么当您编辑新输入时,您会在第一次输入时获得新值,例如jsfiddle.net/37wj5
  • 您必须清除 id(或者,更好的是,在模板块中有明确的代码块)在此处查看可能的答案jsfiddle.net/N9eSN
【解决方案2】:

在add-more函数中加入这一行

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

【讨论】:

    猜你喜欢
    • 2015-08-02
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 2015-04-21
    相关资源
    最近更新 更多