jQuery日期选择器没有在ajax生成的输入字段上工作

我有一个输入字段,它是从服务器端通过Ajax生成的,并插入到当前页面中。 我的问题是:jQuery日期选择器在通过Ajax生成时不在输入字段上工作,但是当字段直接放在页面中时它可以工作。

下面,我提供了我的代码的缩小版本。

HTML代码:

这里是应该激活日期选择器的jQuery代码。

 $.ajax({ type: "GET", url: "/inputfield-loader.php" , success: function(data) { $('#user-form').html(data); $("#datefield").datepicker(); } }); 

这是inputfield-loader.php

 

正如我已经说过的,如果输入字段刚刚硬编码到页面中,这种方法很有效。 但是当作为Ajax调用的返回字符串插入DOM时,日期选择器不再起作用。

任何人都知道如何解决这个问题?

注意我已根据@AkshayKhandelwal的评论更新了问题以包含显示正在发生的事情的代码

试试这样吧

 success: function() { $('#datefield').datepicker(); } 

datepicker不再有效,因为您用新的替换现有的。 因此绑定不再有效,因为引用的datepicker不存在。

在将新的datepicker插入dom后,必须重新绑定日期选择器。

您需要在Ajax成功中重新初始化日期选择器,因为您将现有的替换为newone。

 $.ajax({ type: "POST", url: "path" , success: function(data) { $('#content').html(data); $("#datefield").datepicker(); } , error: function () { alert('Error'); } }); 

希望它有所帮助!

当你使用$.ajax ,也许你应该这样做:

 var _ajax = function(url, data, type){ return $.ajax(url, { data: data type: type }) } 

并使用如下:

 _ajax('handler.ashx', null, 'POST').done(function(response){ // this block of code will execute when `ajax request` is finished ! // for you case: $('#datefield').datepicker(); });