如何为动态添加的元素初始化JQuery插件

时间:2022-11-28 16:23:44

In this JSFiddle, I have two table.inner-table elements which were added initially in the HTML. Spectrum plugin works fine for all of the input.basic elements, that is clicking the element opens the color picker window.

在这个JSFiddle中,我有两个table.inner-table元素,它们最初是在HTML中添加的。 Spectrum插件适用于所有input.basic元素,即单击元素会打开颜色选择器窗口。

BUT this JSFiddle initially has only one table.inner-table element in the HTML. When you click the button labelled Click, another table.inner-table is added. The problem is with both the input.basic elements in this newly added table. Clicking them does not open the color picker window.

但是这个JSFiddle最初在HTML中只有一个table.inner-table元素。单击标记为“单击”的按钮时,将添加另一个table.inner-table。问题在于这个新添加的表中的input.basic元素。单击它们不会打开颜色选择器窗口。

I am suspecting because color picker is already initialized, so it is not working for dynamically added elements. In the JS, the plugin is initialized like this:

我怀疑是因为颜色选择器已经初始化,所以它不适用于动态添加的元素。在JS中,插件初始化如下:

$(".basic").spectrum();

The question is how do I make it work for dynamically added elements?

问题是如何让它适用于动态添加的元素?

WHAT I TRIED:

我做了什么:

I saw this question, and added the following to JS. Did not work =(

我看到了这个问题,并在JS中添加了以下内容。没工作=(

$('body').on('focus', '.basic', function() {
    $(this).spectrum({});
});

1 个解决方案

#1


2  

var table = $('.outer-table > tbody > tr:last').clone();
$(table).find('.sp-replacer').remove();
$('.outer-table > tbody').append(table);
$(".basic").spectrum({});

If you click button, it would re-initialize $(".basic").spectrum({});.

如果单击按钮,它将重新初始化$(“。basic”)。spectrum({});.

Here's a fiddle

这是一个小提琴

#1


2  

var table = $('.outer-table > tbody > tr:last').clone();
$(table).find('.sp-replacer').remove();
$('.outer-table > tbody').append(table);
$(".basic").spectrum({});

If you click button, it would re-initialize $(".basic").spectrum({});.

如果单击按钮,它将重新初始化$(“。basic”)。spectrum({});.

Here's a fiddle

这是一个小提琴