jQuery datepicker不能处理AJAX添加的html元素

时间:2022-11-02 21:07:55

I have a jQuery datepicker function bound to the "birthday" input html element, written in the page header:

我有一个jQuery datepicker函数绑定到“birthday”输入html元素,写在页面头中:

<script type="text/javascript">
    $(function() {
        $( "#birthday" ).datepicker();
    });
</script>

Next, I have some AJAX functionality - it adds new input html element to the page. That element is:

接下来,我有一些AJAX功能——它向页面添加了新的输入html元素。该元素是:

<input type="text" id="birthday" value="" class="detail-textbox1" />

Clicking on that birthday element does not pop up the date picker below the text field. I expected this, as the element is added after the page is loaded, thus it isn't in relation with the function provided in the header.

单击该生日点元素不会弹出文本字段下面的日期选择器。我预料到了这一点,因为元素是在页面加载之后添加的,因此它与页眉中提供的函数没有关系。

How can I make it work? I tried moving the script from the header to the body, but nothing seems to work. Thanks.

我怎么才能让它发挥作用呢?我试着把脚本从标题移动到正文,但似乎什么都不管用。谢谢。

P.S. If I create an input html element with id="birthday" in the page body, everythig works as expected. It appears that only the elements added through AJAX are dysfunctional.

附注:如果我在页面主体中创建一个id="birthday"的输入html元素,那么一切都会按预期进行。似乎只有通过AJAX添加的元素是不正常的。

6 个解决方案

#1


16  

I'm a bit late to the party, but for thoroughness - and with the .live() function being deprecated from jQuery 1.7 onwards - I thought I'd provide an updated solution based on my experiences, and from all the help I got from other answers on *!

我有点晚了,但是为了彻底——并且使用.live()函数从jQuery 1.7开始——我认为我将根据我的经验提供一个更新的解决方案,并且从其他的关于*的答案中得到的帮助!

I had a situation where I needed to add the datepicker functionality to input fields that were being added to the DOM through AJAX calls at random, and I couldn't modify the script making the AJAX calls to attach the datepicker functionality, so I opted for the new shiny .on() function with its delegation features:

我有一个情况我需要输入字段,添加datepicker功能被添加到DOM通过AJAX调用随机,我无法修改脚本进行AJAX调用附加datepicker功能,所以我选择了新亮。()函数及其代表团特点:

// 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", ".my_input_element", function(){

        // as an added bonus, if you are afraid of attaching the "datepicker"
        // multiple times, you can check for the "hasDatepicker" class...
        if (!$(this).hasClass("hasDatepicker"))
        {
            $(this).datepicker();
            $(this).datepicker("show");
        }
    });
});

I hope this helps someone, and thanks for all the answers so far that led me to this solution that worked for me! :)

我希望这能对某些人有所帮助,并感谢到目前为止所有的答案,使我找到了这个对我有效的解决方案!:)

#2


4  

You need to use .live() so that any newly added elements have the event handler attached: http://api.jquery.com/live/

您需要使用.live(),以便任何新添加的元素都附带了事件处理程序:http://api.jquery.com/live/

$('#birthday').bind('load', function() {
    $(this).datepicker();
});

EDIT

编辑

.live() documentation states, that it is a bit out of date. With new versions of jquery (1.7+) use .on().

.live()文档说明,它有点过时了。新版本的jquery(1.7+)使用.on()。

#3


1  

Boris, JK: This was super helpful for me. I have also found that you can use the following for AJAX html if you want to use Datepicker's date range selection:

鲍里斯,JK:这对我非常有帮助。我还发现,如果您想使用Datepicker的日期范围选择,可以使用以下的AJAX html:

$('#groundtransporation').live('focus', function() {
var gt = $( "#rentalPickUp, #rentalDropOff" ).datepicker({
  defaultDate: "+1w",
  changeMonth: true,
  numberOfMonths: 2,
  onSelect: function( selectedDate ) {
    var option = this.id == "rentalPickUp" ? "minDate" : "maxDate",
      instance = $( this ).data( "datepicker" ),
      date = $.datepicker.parseDate(
        instance.settings.dateFormat ||
        $.datepicker._defaults.dateFormat,
        selectedDate, instance.settings );
    gt.not( this ).datepicker( "option", option, date );
  }
});
});

#4


1  

I got another case. My script is copying last table elements including datepicker.

我有另一个例子。我的脚本正在复制包括datepicker在内的最后一个表元素。

The jquery will not working because the copied element has mark that it "hasDatepicker".

jquery不能工作,因为复制的元素标记为“hasDatepicker”。

To activate datepicker in new element, remove that class name and the initiate it, like this.

要在新元素中激活datepicker,请删除类名和初始化名,如下所示。

$("#yournewelementid").attr("class","your-class-name"); $("#yournewelementid").datepicker();

$(" # yournewelementid ").attr(“类”、“your-class-name”);$(" # yournewelementid ").datepicker();

#5


1  

your issue is always happens when elements don't exist when you try to initialize it.

When you use $(function(){/** some code **/}); elements must exsit on the document, it means that has to be on the html so you could can create a function to initialize the component or initialize it on the success event after been add it to the document.

Is important to first add the external html load in the ajax request to the document before you try to initialize it or it won't be initialize at all.
Example:

当尝试初始化元素时,元素不存在时,总是会出现问题。当您使用$(函数(){/**一些代码**/});元素必须存在于文档上,这意味着必须在html上,这样您就可以创建一个函数来初始化组件,或者在将组件添加到文档后的success事件上初始化它。在尝试初始化文档之前,首先将ajax请求中的外部html加载添加到文档中,否则它根本不会被初始化,这一点很重要。例子:

$.ajax({
     url:"ajax_html.html",
     dataType:"html"
}).done(function(html){
     $("#selector").html(html)
     init();
});

美元。ajax({ url:“ajax_html。html”数据类型:“html”}).done(函数(html){ $(“#选择器”). html(html)init();});

function init(){
     $(".birthday").datepicker({});
}

init()函数{ $(“.birthday”).datepicker({ });}

#6


0  

You could initialize the date picker for the newly added element within your ajax success callback:

您可以在ajax success回调中初始化新添加元素的日期选择器:

 $.ajax({

    ...

    success: function(response) {
        if(response.success) {
              $(body).append(response.html);
              $("#birthday").datepicker();
        }
    }
 });

#1


16  

I'm a bit late to the party, but for thoroughness - and with the .live() function being deprecated from jQuery 1.7 onwards - I thought I'd provide an updated solution based on my experiences, and from all the help I got from other answers on *!

我有点晚了,但是为了彻底——并且使用.live()函数从jQuery 1.7开始——我认为我将根据我的经验提供一个更新的解决方案,并且从其他的关于*的答案中得到的帮助!

I had a situation where I needed to add the datepicker functionality to input fields that were being added to the DOM through AJAX calls at random, and I couldn't modify the script making the AJAX calls to attach the datepicker functionality, so I opted for the new shiny .on() function with its delegation features:

我有一个情况我需要输入字段,添加datepicker功能被添加到DOM通过AJAX调用随机,我无法修改脚本进行AJAX调用附加datepicker功能,所以我选择了新亮。()函数及其代表团特点:

// 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", ".my_input_element", function(){

        // as an added bonus, if you are afraid of attaching the "datepicker"
        // multiple times, you can check for the "hasDatepicker" class...
        if (!$(this).hasClass("hasDatepicker"))
        {
            $(this).datepicker();
            $(this).datepicker("show");
        }
    });
});

I hope this helps someone, and thanks for all the answers so far that led me to this solution that worked for me! :)

我希望这能对某些人有所帮助,并感谢到目前为止所有的答案,使我找到了这个对我有效的解决方案!:)

#2


4  

You need to use .live() so that any newly added elements have the event handler attached: http://api.jquery.com/live/

您需要使用.live(),以便任何新添加的元素都附带了事件处理程序:http://api.jquery.com/live/

$('#birthday').bind('load', function() {
    $(this).datepicker();
});

EDIT

编辑

.live() documentation states, that it is a bit out of date. With new versions of jquery (1.7+) use .on().

.live()文档说明,它有点过时了。新版本的jquery(1.7+)使用.on()。

#3


1  

Boris, JK: This was super helpful for me. I have also found that you can use the following for AJAX html if you want to use Datepicker's date range selection:

鲍里斯,JK:这对我非常有帮助。我还发现,如果您想使用Datepicker的日期范围选择,可以使用以下的AJAX html:

$('#groundtransporation').live('focus', function() {
var gt = $( "#rentalPickUp, #rentalDropOff" ).datepicker({
  defaultDate: "+1w",
  changeMonth: true,
  numberOfMonths: 2,
  onSelect: function( selectedDate ) {
    var option = this.id == "rentalPickUp" ? "minDate" : "maxDate",
      instance = $( this ).data( "datepicker" ),
      date = $.datepicker.parseDate(
        instance.settings.dateFormat ||
        $.datepicker._defaults.dateFormat,
        selectedDate, instance.settings );
    gt.not( this ).datepicker( "option", option, date );
  }
});
});

#4


1  

I got another case. My script is copying last table elements including datepicker.

我有另一个例子。我的脚本正在复制包括datepicker在内的最后一个表元素。

The jquery will not working because the copied element has mark that it "hasDatepicker".

jquery不能工作,因为复制的元素标记为“hasDatepicker”。

To activate datepicker in new element, remove that class name and the initiate it, like this.

要在新元素中激活datepicker,请删除类名和初始化名,如下所示。

$("#yournewelementid").attr("class","your-class-name"); $("#yournewelementid").datepicker();

$(" # yournewelementid ").attr(“类”、“your-class-name”);$(" # yournewelementid ").datepicker();

#5


1  

your issue is always happens when elements don't exist when you try to initialize it.

When you use $(function(){/** some code **/}); elements must exsit on the document, it means that has to be on the html so you could can create a function to initialize the component or initialize it on the success event after been add it to the document.

Is important to first add the external html load in the ajax request to the document before you try to initialize it or it won't be initialize at all.
Example:

当尝试初始化元素时,元素不存在时,总是会出现问题。当您使用$(函数(){/**一些代码**/});元素必须存在于文档上,这意味着必须在html上,这样您就可以创建一个函数来初始化组件,或者在将组件添加到文档后的success事件上初始化它。在尝试初始化文档之前,首先将ajax请求中的外部html加载添加到文档中,否则它根本不会被初始化,这一点很重要。例子:

$.ajax({
     url:"ajax_html.html",
     dataType:"html"
}).done(function(html){
     $("#selector").html(html)
     init();
});

美元。ajax({ url:“ajax_html。html”数据类型:“html”}).done(函数(html){ $(“#选择器”). html(html)init();});

function init(){
     $(".birthday").datepicker({});
}

init()函数{ $(“.birthday”).datepicker({ });}

#6


0  

You could initialize the date picker for the newly added element within your ajax success callback:

您可以在ajax success回调中初始化新添加元素的日期选择器:

 $.ajax({

    ...

    success: function(response) {
        if(response.success) {
              $(body).append(response.html);
              $("#birthday").datepicker();
        }
    }
 });