jQuery datepicker在ajax调用后无法正常工作

Jin*_*iel 6 php jquery jquery-ui datepicker

我有以下代码

<html>
    <head>
       //included all jquery related stuff ..not shown here
    </head>
    <body>
       <button id = 'btn' />
       <div id = 'ct'>
             <?php echo file_get_contents('my_ajax_stuff.php'); ?>
       </div>
    </body>
    <script>
       $('.datepicker').datepicker({dateFormat: "dd-mm-yy"});
       $('#btn').click(function() {
           $.ajax({
            type: "GET",
            url: "my_ajax_stuff.php" ,
            success: function(response) {
                $('#ct').html(response);
                /*added following line to solve this issue ..but not worked*/
                //$( ".datepicker" ).datepicker({dateFormat: "dd-mm-yy"});

            } ,
            error: function () {
                $('#ct').html("Some problem fetching data.Please try again");
            }
        });
       });
    </script>
</html>
Run Code Online (Sandbox Code Playgroud)

这页纸

my_ajax_stuff.php

包含一个带有class ='datepicker'的jquery ui datepicker.在第一次加载时,datepicker正常工作.但是当我点击按钮重新加载它时,内容被替换为新内容.但是datepicker不工作.我试过了初始化阿贾克斯成功处理程序内的日期选择器,你see.But也failed.What是issue.How能不能得到解决???

小智 17

你需要reinitialize在Ajax成功的日期选择器

$('.datepicker').datepicker({dateFormat: "dd-mm-yy"});

$('#btn').click(function() {
    $.ajax({
        type: "GET",
        url: "my_ajax_stuff.php" ,
        success: function(response) {

            $('#ct').html(response);
            $( "#datepicker" ).datepicker();
            /*added following line to solve this issue ..but not worked*/
            //$( ".datepicker" ).datepicker({dateFormat: "dd-mm-yy"});

        } ,
        error: function () {
            $('#ct').html("Some problem fetching data.Please try again");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)


Got*_*chi 5

您正在寻找的答案可能类似于这个问题: jQuery datepicker won't work on a AJAX added html element

您正在用 ajax 响应替换 DOM 中的 datepicker 元素。这第一次起作用的原因是 PHP 在第一次加载时渲染了 my_ajax_stuff.php 已经在 HTML 中,因此它在 DOM 中可供 jQuery 使用。

// 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", ".datepicker", function(){
            $(this).datepicker();
            $(this).datepicker("show");
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 我会过滤它以防万一:`$("body").on("click", ".datepicker:not(.hasDatepicker)", function(){...});` (2认同)