jQuery 日期选择器不适用于 AJAX 添加的 html 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4812784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:58:04  来源:igfitidea点击:

jQuery datepicker won't work on a AJAX added html element

htmlajaxjquery

提问by Boris

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

我有一个 jQuery datepicker 函数绑定到“生日”输入 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 birthdayelement 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.

PS 如果我在页面正文中创建一个带有 id="birthday" 的输入 html 元素,那么一切都会按预期工作。似乎只有通过 AJAX 添加的元素是功能失调的。

回答by Chris Kempen

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

我参加聚会有点晚了,但为了彻底 - 并且该.live()功能从 jQuery 1.7开始被弃用- 我想我会根据我的经验提供更新的解决方案,以及我从其他答案中获得的所有帮助堆栈溢出!

I had a situation where I needed to add the datepickerfunctionality 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 datepickerfunctionality, so I opted for the new shiny .on()function with its delegation features:

我有一种情况,我需要将datepicker功能添加到通过 AJAX 调用随机添加到 DOM 的输入字段中,并且我无法修改使 AJAX 调用附加datepicker功能的脚本,所以我选择了新的.on()具有委托功能的闪亮功能:

// 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! :)

我希望这对某人有所帮助,并感谢迄今为止的所有答案,这些答案使我找到了对我有用的解决方案!:)

回答by JK.

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() documentationstates, that it is a bit out of date. With new versions of jquery (1.7+) use .on().

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

回答by Ahmad

I got another case. My script is copying last table elements including 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.

要在新元素中激活日期选择器,请删除该类名并启动它,如下所示。

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

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

回答by David

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:

当您尝试初始化元素不存在时,您的问题总是会发生。

当你使用$(function(){ /** some code **/}); 元素必须存在于文档中,这意味着必须在 html 上,以便您可以创建一个函数来初始化组件或在将其添加到文档后在成功事件上对其进行初始化。

在尝试初始化文档之前,首先将 ajax 请求中的外部 html 加载添加到文档中很重要,否则它根本不会被初始化。
例子:

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

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

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

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

回答by adrian

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:

Boris, 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 );
  }
});
});

回答by cweston

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

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

 $.ajax({

    ...

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