bootstrap dateTime picker plugin on dynamic added element

萝らか妹 提交于 2020-01-03 03:10:07

问题


I am new to jquery i have added bootstrap datetime plugin on an element after dom load i am adding an element which having same class by which datetime plugin is being called. But unable to call plugin an no console error found.


回答1:


Because you probably bound datePicker on ready event.

The best solution imo would be to bind DatePicker just after you create that element. So:

var myDynamicElementCreateFunction = function () {
    // ...
    var $elem = $('<div/>'); // Create your element
    $('#my-elem-container').append($elem);
    $elem.datepicker();
}

The second solution would be to use .on() event binding.

$(function () {
    $('#my-elem-container').on('click', '.my-elem-selector', function () {
        var $this = $(this);
        $this.datePicker(); // You should probably check whether datapicker is already attached before binding it. 
    });
});

I didn't use datepicker so I don't know if it provides a way to check whether it's already attached to an element. You could try it by checking if $('#my-element').datePicker exists. If that doesn't work you can always make some kind of hash map to track these.

Maybe even datepicker is smart enough to know not to reinitialize twice on same element.

Have in mind that first solution is much better and cleaner imo and you should use it if possible.



来源:https://stackoverflow.com/questions/22164812/bootstrap-datetime-picker-plugin-on-dynamic-added-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!