简体   繁体   English

如何为动态添加到DOM的元素初始化DateTimePicker?

[英]How to initialize DateTimePicker for elements added to the DOM on the fly?

I need to initialize a Bootstrap-DateTimePicker for inputs using jquery class-selector for elements that were created on the fly. 我需要使用jquery类选择器为动态创建的元素初始化Bootstrap-DateTimePicker用于输入。

Typically, I would initialize the datetime picker for elements that were created when page is ready like so 通常,我会为页面准备好后创建的元素初始化日期时间选择器,如下所示

$('.date-picker').datetimepicker({
     format: 'D/M/YYYY',
     useCurrent: false
});

But now I need to also apply the same thing on elements that were created on the dynamically. 但是现在,我还需要对动态创建的元素应用相同的内容。 To get that to work, I did the following hack 为了使它起作用,我做了以下修改

$(document).on('focus', '.date-picker', function(){
    $(this).datetimepicker({
        format: 'D/M/YYYY',
        useCurrent: false
    });
});

The above code work only when you focus on the input which then it initialize the date time picker. 上面的代码仅在您专注于输入时才起作用,然后它初始化日期时间选择器。

The issue with the above code, is that when an input has a "incorrectly formatted" default value, the format does not change. 上面的代码的问题在于,当输入具有“格式错误”的默认值时,格式不会更改。 In another word, when the page is loaded the input does not have the DateTime bounded to it. 换句话说,加载页面时,输入没有绑定到DateTime。

I tried to call the focus() event on page load, but that does not seems to be working either. 我试图在页面加载时调用focus()事件,但这似乎也不起作用。 This is what I tried 这是我尝试过的

$(document).on('focus', '.date-picker', function(){
    $(this).datetimepicker({
        format: 'D/M/YYYY',
        useCurrent: false
    });
}).focus();

How can I initialize the datetimepicker for predefined elements and elements that were dynamically created after page load? 如何为预定义元素和页面加载后动态创建的元素初始化datetimepicker?

I created the following fiddle to show how the datetime is not initialized on page load https://jsfiddle.net/516zsh7b/510/ 我创建了以下小提琴,以显示如何在页面加载时不初始化日期时间https://jsfiddle.net/516zsh7b/510/

Well, the best way would be to know how/when you add these new elements and add the logic there... 好吧,最好的方法是知道如何/何时添加这些新元素并在其中添加逻辑...

If you really need a reactive way to run a piece of JS code when an element is added to DOM, you could try mutation observers (not the best for performance): http://ryanmorr.com/using-mutation-observers-to-watch-for-element-availability/ 如果在将元素添加到DOM时确实需要一种反应性的方式来运行一段JS代码,则可以尝试使用突变观察器(不是性能最佳的观察器): http : //ryanmorr.com/using-mutation-observers-to -watch换元件可用性/

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

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