jQuery datepicker不适用于AJAX添加的html元素

Bor*_*ris 9 html ajax jquery

我有一个jQuery datepicker函数绑定到"birthday"输入html元素,写在页眉中:

<script type="text/javascript">
    $(function() {
        $( "#birthday" ).datepicker();
    });
</script>
Run Code Online (Sandbox Code Playgroud)

接下来,我有一些AJAX功能 - 它向页面添加了新的输入html元素.那个元素是:

<input type="text" id="birthday" value="" class="detail-textbox1" />
Run Code Online (Sandbox Code Playgroud)

单击该生日元素不会弹出文本字段下方的日期选择器.我期望这样,因为在页面加载后添加了元素,因此它与标题中提供的功能无关.

我怎样才能使它工作?我尝试将脚本从标题移动到正文,但似乎没有任何效果.谢谢.

PS如果我在页面正文中创建id ="birthday"的输入html元素,则everythig按预期工作.似乎只有通过AJAX添加的元素功能失调.

Chr*_*pen 17

我有点迟到了,但是为了彻底 - 并且从jQuery 1.7开始不推荐使用该.live()功能- 我想我会根据自己的经验提供更新的解决方案,并从我从其他答案得到的所有帮助中提供堆栈溢出!

我有一种情况,我需要datepicker通过随机的AJAX调用添加到DOM的输入字段的功能,我无法修改脚本使AJAX调用附加datepicker功能,所以我选择了新的闪亮.on()功能及其授权功能:

// do this once the DOM's available...
$(function(){

    // this line will add an event handler to the selected inputs, both
    // current and future, whenever they are clicked...
    // this is delegation at work, and you can use any containing element
    // you like - I just used the "body" tag for convenience...
    $("body").on("click", ".my_input_element", function(){

        // as an added bonus, if you are afraid of attaching the "datepicker"
        // multiple times, you can check for the "hasDatepicker" class...
        if (!$(this).hasClass("hasDatepicker"))
        {
            $(this).datepicker();
            $(this).datepicker("show");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

我希望这对某人有所帮助,并感谢迄今为止的所有答案,这使我找到了适合我的解决方案!:)


JK.*_*JK. 4

您需要使用 .live() 以便任何新添加的元素都附加事件处理程序:http://api.jquery.com/live/

$('#birthday').bind('load', function() {
    $(this).datepicker();
});
Run Code Online (Sandbox Code Playgroud)

编辑

.live() 文档指出,它有点过时了。对于新版本的 jquery (1.7+),请使用.on()

  • 谢谢JK。使用 .live() 解决了这个问题。我没有使用您的示例,而是使用 $('#birthday').live('focus', function() { $(this).datepicker(); }); (2认同)