jQuery UI DatePicker 未出现在通过 Ajax 加载的 Bootbox 模式中

jQuery UI DatePicker not appearing inside Bootbox modal loaded through Ajax

我需要将表单动态加载到 Bootbox 模态 window。我正在通过 Ajax 加载表格。表单中有一个 jQuery UI 日期选择器字段。

使用浏览器的调试器,当通过 Ajax 加载表单时,我可以看到添加到 DOM 的日期选择器元素。但是,单击该字段不会执行任何操作。日历没有出现,更重要的是,日期选择器 DOM 元素不会像我直接在页面上加载日期选择器字段时那样发生变化。

这是我在索引页的 Ajax 调用:

$.ajax({
    type: "post",
    timeout: "100000",
    url: "/cfc/site_functions.cfc",
    beforeSend: function (){ 
        bootbox.dialog({
            message: "Loading...",
            title: modal_title,
            onEscape:false,
            backdrop:true,
            closeButton:true,
            buttons: {
                "Cancel": {}
            }
        });
    },
    data: {
        method: "buildMyForm"
    },
    success: function(objResponse){
        $(".bootbox-body").html(objResponse);
    },
    error: function(xhr, ajaxOptions, thrownError){
        $(".bootbox-body").html("Error loading form.");
    }
});

这是构建表单并初始化日期选择器字段的 Ajax 调用所调用的 Coldfusion 函数:

<cffunction name="buildMyForm" access="remote" returntype="any" returnformat="plain">

    <cfsavecontent variable="local.buildMyForm">

        <script type="text/javascript">
            $(document).ready(function(e) {
                $("#date_posted").datepicker({
                    showAnim: "slide"
                });
            });
        </script>

        <cfoutput>

            <form method="post" id="edit_form" name="edit_form">

                <div class="form-group">
                    <label for="date_posted" class="required">Date</label>
                    <input type="text" class="form-control" id="date_posted" name="date_posted" required autocomplete="off">
                </div>

            </form>

        </cfoutput>
    </cfsavecontent>

    <cfreturn local.buildMyForm>
</cffunction>

有没有想过为什么日期选择器元素会初始化,但在您单击日期字段时却不起作用?有一个类似的问题,但它的解决方案是更新 CSS 因为日期选择器日历显示的 z-index 低于 Bootbox 模态。但是,在我的例子中,当您单击日期字段时,日期选择器元素根本没有被填充,所以这不仅仅是它被隐藏的问题。

感谢@EdenSource 帮助缩小问题范围。

日期选择器代码何时触发似乎存在一些竞争。我更新了 CFC 中的 javascript(由 ajax 函数调用以构建表单的代码)并且它有效:

<script type="text/javascript">
    $(document).ready(function(e) {
        $("#date_posted").on("focus",function(){
            if(!$(this).hasClass("hasDatepicker")){
                $(this).datepicker({
                    showAnim: "slide"
                });
                $(this).addClass("hasDatepicker");
                $(this).datepicker("show");
            }
        });
    });
</script>