JQuery日期选择器在ajax调用后不起作用

2022-01-05 00:00:00 jquery php jquery-ui datepicker

我有以下代码

<头>//包括所有jquery相关的东西..这里没有显示<身体><按钮 id = 'btn'/>

<?php echo file_get_contents('my_ajax_stuff.php');?>

<脚本>$('.datepicker').datepicker({dateFormat: "dd-mm-yy"});$('#btn').click(function() {$.ajax({类型:获取",url: "my_ajax_stuff.php" ,成功:功能(响应){$('#ct').html(响应);/*添加以下行来解决这个问题..但没有奏效*///$( ".datepicker" ).datepicker({dateFormat: "dd-mm-yy"});} ,错误:函数(){$('#ct').html("获取数据时出现问题,请重试");}});});

页面

<块引用>

my_ajax_stuff.php

包含一个类 = 'datepicker' 的 jquery ui datepicker.在第一次加载时,datepicker 可以工作.但是当我再次单击按钮重新加载时,内容被新内容替换.但是 datepicker 不起作用.我已经尝试在 ajax 成功处理程序中初始化日期选择器,如您所见.但它也失败了.这是什么问题.如何解决???

解决方案

你需要重新初始化Ajax成功中的日期选择器

$('.datepicker').datepicker({dateFormat: "dd-mm-yy"});$('#btn').click(function() {$.ajax({类型:获取",url: "my_ajax_stuff.php" ,成功:功能(响应){$('#ct').html(响应);$( "#datepicker" ).datepicker();/*添加以下行来解决这个问题..但没有奏效*///$( ".datepicker" ).datepicker({dateFormat: "dd-mm-yy"});} ,错误:函数(){$('#ct').html("获取数据时出现问题,请重试");}});});

I have the following code

<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>

The page

my_ajax_stuff.php

contains a jquery ui datepicker with class = 'datepicker'.On the first load the datepicker works.But when I click on the button to reload it again , the contents are replaced with new contents.But the datepicker is not working.I have tried initialising the datepicker inside the ajax success handler ,as you see.But it also failed.What is the issue.How can it be solved???

解决方案

You need to reinitialize the date picker in Ajax success

$('.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");
        }
    });
});

相关文章