简体   繁体   English

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

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

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!非常感谢您的帮助!

here is the trick:这是诀窍:

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

DEMO演示

The $('...selector..').on('..event..', '...another-selector...', ...callback...); $('...selector..').on('..event..', '...another-selector...', ...callback...); syntax means:语法意思是:
Add a listener to ...selector.. (the body in our example) for the event ..event.. ('focus' in our example).为事件..event.. (在我们的示例中为“focus”)向...selector.. (我们示例中的body )添加一个侦听...selector.. For all the descendants of the matching nodes that matches the selector ...another-selector... ( .datepicker_recurring_start in our example) , apply the event handler ...callback... (the inline function in our example)对于匹配选择器...another-selector... (在我们的示例中为.datepicker_recurring_start )的匹配节点的所有后代,应用事件处理程序...callback... (在我们的示例中为内联函数)

See http://api.jquery.com/on/ and especially the section about "delegated events"请参阅http://api.jquery.com/on/ ,尤其是有关“委托事件”的部分

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 都不同

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();
    }

});

Make sure your element with the .date-picker class does NOT already have a hasDatepicker class.确保带有.date-picker hasDatepicker类的元素还没有hasDatepicker类。 If it does, even an attempt to re-initialize with $myDatepicker.datepicker();如果是这样,甚至尝试使用$myDatepicker.datepicker();重新初始化$myDatepicker.datepicker(); will fail!将失败! Instead you need to do...相反,你需要做...

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

You need to run the .datepicker();你需要运行.datepicker(); again after you've dynamically created the other textbox elements.在您动态创建其他文本框元素后再次。

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();
});

The new method for dynamic elements is MutationsObserver .. The following example uses underscore.js to 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
});

This was what worked for me (using jquery datepicker):这对我有用(使用 jquery datepicker):

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

None of the other solutions worked for me.其他解决方案都不适合我。 In my app, I'm adding the date range elements to the document using jquery and then applying datepicker to them.在我的应用程序中,我使用 jquery 将日期范围元素添加到文档中,然后将 datepicker 应用于它们。 So none of the event solutions worked for some reason.因此,由于某种原因,没有一个事件解决方案有效。

This is what finally worked:这是最终奏效的:

$(document).on('changeDate',"#elementid", function(){
    alert('event fired');
});

Hope this helps someone because this set me back a bit.希望这对某人有所帮助,因为这让我有点退缩。

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

I have modified @skafandri answer to avoid re-apply the datepicker constructor to all inputs with .datepicker_recurring_start class.我已经修改@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这是一个工作演示

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/

$( ".datepicker_recurring_start" ).each(function(){
    $(this).datepicker({
        dateFormat:"dd/mm/yy",
        yearRange: '2000:2012',
        changeYear: true,
        changeMonth: true
    });
});
 $('body').on('focus',".my_date_picker", function(){
            $(this).datepicker({
                minDate: new Date(),
            });
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM