Newly added elements using delegate() won't bind jscolor.js

随声附和 提交于 2019-12-03 15:52:43

There are several problem to your code:

  1. You are using IDs in your "line" variable. ID must be unique within an HTML document. You'd better use name attributes, or create a new line differently so you can change the IDs.

  2. Why do you delegate the 'click' event for the 'Add' button ? Event delegation is used be able to automatically "bind" events to elements created dynamically. In your example, the "Add" button, is static to the page, you don't need to use delegate, simply .click() or .bind().

  3. After creating the new line, you have to explicitly initialize your jscolor on the new field, it's not going to happen automatically. When your page is first parsed, the existing <input class="color" /> are initialized by the jscolor plugin, but insterted elements afterwards are not anymore, the script has run already.

Here's some modified code:

<script> 
    var line = '<li class="form_line" id="line"><span><label>Item:</label><input type="text" required="required" placeholder="what item is this?" name="item"></span><span><label>Amount: </label><input required="required" type="number" name="amount"></span><span><label>Color: </label><input type="text" required="required" class="color {pickerClosable:true, hash:true ,pickerFace:3,pickerBorder:0}" name="color"></span></li>';

    $(document).ready(function() {

       var $ul = $('#formulario'); // the UL, select it once and r-use this selection

       $('.add').click(function(e) {
           var $line = $(line);
           $line.appendTo($ul);

           // initialize the new jscolor instance
           new jscolor.color($line.find('input[name=color]')[0], {});

       });


    }); //end of main func 
</script>

And this jsfiddle for testing.

You could solve this by reinitialize the jscolor object in the append event.

$("body").on('click', 'div .add', function(){
     $("#some-id").append('<input type="text" name="color" class="color">');
     new jscolor.init();
});

No other solution works for me.

Following solution works for me.
Just create new jscolor object by passing input element object in javascript.

var picker = new jscolor($li.find('.jscolor')[0]);

reference from http://jscolor.com/examples/ go to Instantiating new Color Pickers section.

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