5

我有一个简单的表格,每行包含 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..?

非常感谢任何帮助。

4

3 回答 3

3

您的代码有几个问题:

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

  2. 为什么要为“添加”按钮委托“点击”事件?事件委托用于能够自动将事件“绑定”到动态创建的元素。在您的示例中,“添加”按钮对于页面是静态的,您不需要使用委托,只需 .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>

而这个jsfiddle用于测试。

于 2011-12-03T09:26:19.800 回答
1

您可以通过在附加事件中重新初始化 jscolor 对象来解决此问题。

$("body").on('click', 'div .add', function(){
     $("#some-id").append('<input type="text" name="color" class="color">');
     new jscolor.init();
});
于 2014-03-02T05:38:29.700 回答
0

没有其他解决方案适合我。

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

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

来自http://jscolor.com/examples/的参考转到实例化新的拾色器部分。

于 2017-06-02T17:31:06.287 回答