简体   繁体   中英

How to initialize a JQuery plugin for elements added dynamically

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.

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 .

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:

$(".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 =(

$('body').on('focus', '.basic', function() {
    $(this).spectrum({});
});
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({}); .

Here's a fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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