新增元素使用delegate() won't bind jscolor.js

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

本文关键字:bind js jscolor won 元素 delegate 新增      更新时间:2023-09-26

我有一个简单的表单,其中每行由3个输入字段组成。在其中一个字段上,我使用jscolor.js(字段有一个class="color",因此绑定了JS)。

然而,当我使用jQuery的delegate()添加新行时,输入字段不绑定JS,预期的功能不存在。http://jsfiddle.net/alexwald/qARzP/

<script>
var line = '<li class="form_line" id="line">    
              <span>
                <label for="item">Item:</label>
                <input type="text" required="required" placeholder="what item is this?" id="item" name="item[]>
              </span>
              <span>
                <label for="amount">Amount: </label>
                <input required="required"  type="number" id="amount" name="amount[]>
              </span>
              <span>
                <label for="color">Color: </label>
                <input type="text" required="required" class="color {pickerClosable:true, hash:true ,pickerFace:3,pickerBorder:0}" id="color" name="color[]">
              </span>
            </li>';
$(document).ready(function() {          
  $("form").delegate(".add", "click", function(){        
    $('ul').append(line); 
  }); // end of adding                              
}); //end of main func 
</script>

我认为问题在:

  • 如何定义line变量,或
  • 我使用一个不合适的选择器与.delegate,所以它应该是别的东西,而不是form ..?

感谢您的帮助。

你的代码有几个问题:

  1. 你在你的"line"变量中使用id。ID在HTML文档中必须是唯一的。您最好使用名称属性,或者创建不同的新行,以便您可以更改id。

  2. 为什么要将'click'事件委托给'Add'按钮?事件委托用于自动将事件"绑定"到动态创建的元素。在你的例子中,"添加"按钮,是静态的页面,你不需要使用委托,只需。click()或。bind()。

  3. 创建新行后,必须在新字段上显式初始化jscolor,这不会自动发生。当你的页面第一次被解析时,现有的<input class="color" />被jscolor插件初始化,但是之后插入的元素不再初始化,脚本已经运行了。

下面是一些修改后的代码:

<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>

您可以通过在append事件中重新初始化jscolor对象来解决这个问题。

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

我没有别的办法了。

以下解决方案适用于我。
通过在javascript中传递输入元素对象创建新的jscolor对象。

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

参考http://jscolor.com/examples/转到实例化新的颜色选择器一节。