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

时间:2015-05-14 11:14:29

标签: javascript jquery ajax

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

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

HTML code:

<form id="user-form"></form>

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

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

这里inputfield-loader.php

<input type="text" name="firstname" id="firstname"></div>
<div><input type="text" name="email" id="email"></div>
<div><input type="text" name="birthdate" id="datefield"></div>
<div><input type="submit"></div>

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

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

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

4 个答案:

答案 0 :(得分:2)

试试这个

worker.postMessage

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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

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

希望它有所帮助!

答案 3 :(得分:1)

当您使用$.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();
 });