html - jQuery 日期选择器不适用于 AJAX 添加的 html 元素

标签 html ajax jquery

我有一个绑定(bind)到“生日”输入 html 元素的 jQuery 日期选择器函数,写在页眉中:

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

接下来,我有一些 AJAX 功能 - 它将新的输入 html 元素添加到页面。该元素是:

<input type="text" id="birthday" value="" class="detail-textbox1" />

单击该生日 元素不会在文本字段下方弹出日期选择器。我预料到了这一点,因为该元素是在页面加载后添加的,因此它与 header 中提供的功能无关。

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

附言如果我在页面主体中创建一个带有 id="birthday"的输入 html 元素,everythig 将按预期工作。似乎只有通过 AJAX 添加的元素功能失调。

最佳答案

我来晚了一点,但为了彻底 - .live() 函数是 deprecated from jQuery 1.7以后 - 我想我会根据我的经验以及我从 StackOverflow 上的其他答案获得的所有帮助提供更新的解决方案!

我遇到过这样一种情况,我需要将 datepicker 功能添加到通过 AJAX 调用随机添加到 DOM 的输入字段,但我无法修改进行 AJAX 调用的脚本附加 datepicker 功能,所以我选择了新的 Shiny .on() 函数及其委托(delegate)功能:

// 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");
        }
    });
});

我希望这对某人有所帮助,并感谢到目前为止所有的答案,这些答案让我找到了这个对我有用的解决方案! :)

关于html - jQuery 日期选择器不适用于 AJAX 添加的 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4812784/

相关文章:

javascript - 形式不吸收新的值(value)

html - 如何默认启用深色主题,而不是切换按钮?

javascript - 确定 ajax 调用已完成以运行另一个 ajax 调用

javascript - 将 'Drop-Zone' 与 'regular file-input' 组合

javascript - 上传文件时向 Jquery.Ajax post 添加数据?

php - uploadify jQuery 和 javascript 的问题

javascript - jQuery 选择器中逗号的含义是什么

javascript - 概括一个专门的 JQuery 函数

html - 如何同步循环遍历 indexedDB 表?

javascript - 如何相乘并检查新插入行的字段