jQuery的.clone(true,true)不是克隆对子节点的事件绑定 [英] jQuery's .clone(true, true) not cloning event bindings on children

查看:332
本文介绍了jQuery的.clone(true,true)不是克隆对子节点的事件绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用clone(true,true)复制select和一些按钮进行克隆和删除。
我认为第二个真正的参数应该确保将事件处理程序传递给克隆的子按钮。

I'm using clone(true, true) to copy a select and some buttons to clone and remove. I thought the second true argument should ensure that the event handler is passed on to the cloned child buttons.

这是标记:

<div id="clone-container">
    <div class="clone">
        <label for="select1">Select 1</label>
        <select id="select1" name="select1" class="">
            <option>Select One:</option>
            <option value="1">1</option>
        </select>
        <span class="controls">
            <a href="#" class="btn add">+</a>
            <a href="#" class="btn remove">−</a>
        </span>
    </div>
</div>​

并且js:

var $cloned = $('.clone').clone(true, true);
var $addButton = $(".btn.add");
$addButton.on("click", function(e) {
    e.preventDefault();
    var $cloner = $(this).closest(".clone");    
    $cloned.clone().insertAfter($cloner);
});​

这里有一个js小提琴:
http://jsfiddle.net/cjmemay/yXA4R /

And here is a js fiddle: http://jsfiddle.net/cjmemay/yXA4R/

推荐答案

您的代码存在两个问题:

There are two problems with your code:


  1. 原始克隆( $ cloned )没有绑定到按钮的事件监听器

  2. 您第二次调用 clone 不会保留事件

  1. The original clone ($cloned) does not have an event listener bound to the button
  2. Your second invocation of clone does not preserve events

您需要克隆之后的容器您已将事件侦听器附加到按钮。此外,您需要将 true 参数传递给第二次调用 clone

You need to clone the container after you have attached the event listener to the button. Additionally, you need to pass the true arguments to the second invocation of clone:

var $addButton = $(".btn.add");
$addButton.on("click", function(e) {
    e.preventDefault();
    var $cloner = $(this).closest(".clone");    
    $cloned.clone(true, true).insertAfter($cloner);
});
var $cloned = $('.clone').clone(true, true);

这是一个演示: http://jsfiddle.net/3hjfj/

这篇关于jQuery的.clone(true,true)不是克隆对子节点的事件绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆