Javascript 将 datepicker() 放在动态创建的元素上 - JQuery/JQueryUI

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10433154/
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-24 01:17:57  来源:igfitidea点击:

putting datepicker() on dynamically created elements - JQuery/JQueryUI

javascriptjqueryjquery-uidatepicker

提问by steeped

I have dynamically created textboxes, and I want each of them to be able to display a calendar on click. The code I am using is:

我已经动态创建了文本框,我希望每个文本框都能够在点击时显示日历。我正在使用的代码是:

$(".datepicker_recurring_start" ).datepicker();

Which will only work on the first textbox, even though all my textboxes have a class called datepicker_recurring_start.

这只适用于第一个文本框,即使我所有的文本框都有一个名为 datepicker_recurring_start 的类。

Your help is much appreciated!

非常感谢您的帮助!

回答by ilyes kooli

here is the trick:

这是诀窍:

$('body').on('focus',".datepicker_recurring_start", function(){
    $(this).datepicker();
});?

DEMO

演示

The $('...selector..').on('..event..', '...another-selector...', ...callback...);syntax means:
Add a listener to ...selector..(the bodyin our example) for the event ..event..('focus' in our example). For all the descendants of the matching nodes that matches the selector ...another-selector...(.datepicker_recurring_startin our example) , apply the event handler ...callback...(the inline function in our example)

$('...selector..').on('..event..', '...another-selector...', ...callback...);语法手段:
添加一个监听器...selector..(在body我们的例子)的事件..event..(“焦点”在我们的例子)。对于与选择器匹配的匹配节点的所有后代...another-selector....datepicker_recurring_start在我们的示例中),应用事件处理程序...callback...(在我们的示例中为内联函数)

See http://api.jquery.com/on/and especially the section about "delegated events"

请参阅http://api.jquery.com/on/,尤其是有关“委托事件”的部分

回答by Tapash

For me below jquery worked:

对我来说,下面的 jquery 有效:

changing "body" to document

将“正文”更改为文档

$(document).on('focus',".datepicker_recurring_start", function(){
    $(this).datepicker();
});

Thanks to skafandri

感谢skafandri

Note: make sure your id is different for each field

注意:确保每个字段的 id 都不同

回答by pleshy

Excellent answer by skafandri +1

skafandri +1 的出色回答

This is just updated to check for hasDatepicker class.

这只是更新以检查 hasDatepicker 类。

$('body').on('focus',".datepicker", function(){

    if( $(this).hasClass('hasDatepicker') === false )  {
        $(this).datepicker();
    }

});

回答by wintondeshong

Make sure your element with the .date-pickerclass does NOT already have a hasDatepickerclass. If it does, even an attempt to re-initialize with $myDatepicker.datepicker();will fail! Instead you need to do...

确保您的.date-picker类元素还没有hasDatepicker类。如果是这样,即使尝试重新初始化$myDatepicker.datepicker();也会失败!相反,你需要做...

$myDatepicker.removeClass('hasDatepicker').datepicker();

回答by Tr1stan

You need to run the .datepicker();again after you've dynamically created the other textbox elements.

您需要.datepicker();在动态创建其他文本框元素后再次运行。

I would recommend doing so in the callback method of the call that is adding the elements to the DOM.

我建议在将元素添加到 DOM 的调用的回调方法中这样做。

So lets say you're using the JQuery Load method to pull the elements from a source and load them into the DOM, you would do something like this:

因此,假设您正在使用 JQuery Load 方法从源中提取元素并将它们加载到 DOM 中,您将执行以下操作:

$('#id_of_div_youre_dynamically_adding_to').load('ajax/get_textbox', function() {
  $(".datepicker_recurring_start" ).datepicker();
});

回答by Hady Shaltout

The new method for dynamic elements is MutationsObserver.. The following example uses underscore.jsto use ( _.each ) function.

动态元素的新方法是MutationsObserver.. 以下示例使用underscore.js来使用 ( _.each ) 函数。

MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;    

var observerjQueryPlugins = new MutationObserver(function (repeaterWrapper) {

    _.each(repeaterWrapper, function (repeaterItem, index) {

        var jq_nodes = $(repeaterItem.addedNodes);

        jq_nodes.each(function () {

            // Date Picker
            $(this).parents('.current-repeateritem-container').find('.element-datepicker').datepicker({
                dateFormat: "dd MM, yy",
                showAnim: "slideDown",
                changeMonth: true,
                numberOfMonths: 1
            });

        });

    });

});

observerjQueryPlugins.observe(document, {
    childList: true,
    subtree: true,
    attributes: false,
    characterData: false
});

回答by Vinicius Avelino Alcantara

This was what worked for me (using jquery datepicker):

这对我有用(使用 jquery datepicker):

$('body').on('focus', '.datepicker', function() {
 $(this).removeClass('hasDatepicker').datepicker();
});

回答by Nada N. Hantouli

you can add the class .datepicker in a javascript function, to be able to dynamically change the input type

您可以在 javascript 函数中添加类 .datepicker,以便能够动态更改输入类型

 $("#ddlDefault").addClass("datepicker");
 $(".datepicker").datetimepicker({ timepicker: false, format: 'd/m/Y', });

回答by c0x6a

I have modified @skafandri answer to avoid re-apply the datepickerconstructor to all inputs with .datepicker_recurring_startclass.

我已经修改了@skafandri 的答案,以避免将datepicker构造函数重新应用于所有带有.datepicker_recurring_start类的输入。

Here's the HTML:

这是 HTML:

<div id="content"></div>
<button id="cmd">add a datepicker</button>

Here's the JS:

这是JS:

$('#cmd').click(function() {
  var new_datepicker = $('<input type="text">').datepicker();
  $('#content').append('<br>a datepicker ').append(new_datepicker);
});

here's a working demo

这是一个工作演示

回答by Mauricio Gracia Gutierrez

This is what worked for me on JQuery 1.3 and is showing on the first click/focus

这是在 JQuery 1.3 上对我有用的方法,并且在第一次单击/焦点时显示

function vincularDatePickers() {
    $('.mostrar_calendario').live('click', function () {
        $(this).datepicker({ showButtonPanel: true, changeMonth: true, changeYear: true, showOn: 'focus' }).focus();
    });
}

this needs that your input have the class 'mostrar_calendario'

这需要您的输入具有“mostrar_calendario”类

Live is for JQuery 1.3+ for newer versions you need to adapt this to "on"

Live 适用于 JQuery 1.3+ 的较新版本,您需要将其调整为“on”

See more about the difference here http://api.jquery.com/live/

在此处查看有关差异的更多信息http://api.jquery.com/live/