dateTime选择器插件在动态添加元素

dateTime选择器插件在动态添加元素

本文介绍了bootstrap dateTime选择器插件在动态添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jquery的新手,在dom加载之后,我已经在一个元素上添加了bootstrap datetime插件,我添加了一个与datetime插件正在被调用的类相同的元素。但是无法调用插件,找不到控制台错误。

解决方案

因为你可能在 / code>事件。



最好的解决方案是在创建该元素之后绑定DatePicker。所以:

  var myDynamicElementCreateFunction = function(){
// ...
var $ elem = $( '< DIV />'); //创建元素
$('#my-elem-container')。append($ elem);
$ elem.datepicker();
}

第二个解决方案是使用 .on( ) var $ this = $(this);
$ this.datePicker(); //你应该检查datapicker是否已经绑定之前已经附加
});
});

我没有使用datepicker,所以我不知道它是否提供了一种方法来检查是否已经附加到元素上您可以通过检查 $('#my-element')。datePicker 是否存在。
如果这不起作用,你可以随时使用某种哈希映射来跟踪这些。



也许甚至datepicker是聪明的,知道不重新初始化两次在同一个元素上。



请记住,第一个解决方案是更好和更清洁的imo,如果可能,您应该使用它。


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.

解决方案

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.

这篇关于bootstrap dateTime选择器插件在动态添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:52