javascript - jQuery .clone(true, true) 不克隆事件

标签 javascript jquery clone

我正在编写这段代码,由于我不太擅长 jQuery,所以我发现自己陷入了困境。

var row_clone_index = 1;
function Row_clone() {
    var cloned_row = $(this).parent().parent().clone(true, true);
    cloned_row.css('display', 'none');
    cloned_row.delay(100).queue(function(next){
        cloned_row.css('display', '');
        next();
    });
    $(this).removeClass("row-clone");

    var html = cloned_row.html().replace(/new/g, "new" + row_clone_index);
    cloned_row.html(html);

    cloned_row.find("select,input").each(function() {
        if (!$(this).hasClass("preserved")) {
            if (!$(this).attr("id")) {
                $(this).val("");
            } else {
                match = $(this).attr("id").match(/((start|stop)holiday_new)[0-9]*_(calendar(month|year))/);
                if (match) {
                    id = match[1] + "_" + match[3];
                    $(this).val($("#" + id).val());
                } else {
                    if ($(this).attr("type") == "checkbox") {
                        $(this).removeAttr("checked");
                    } else if ($(this).attr("id").match(/(start|stop)holiday_new.*/)) {
                        $(this).val("");
                    } else if ($(this).attr("id").search(/day/) == -1) {
                        $(this).val("");
                    }
                }
            }
        }
    });
    $(this).parent().parent().after(cloned_row);
    row_clone_index = parseInt(row_clone_index) + 1;
};

我想做的是在元素发生变化时克隆它(在 .change() 上调用 Row_clone 函数)。但是在克隆后与该元素交互时应该发生的事件不会发生。

我尝试将 .after 移到末尾(它之前位于函数的开头,但没有改变任何内容)。

感谢您的帮助!

最佳答案

看起来您克隆的是正确的,但是之后,您还更改了该元素的 HTML,这很可能会使您之前克隆的所有绑定(bind)无效:

var html = cloned_row.html().replace(/new/g, "new" + row_clone_index);
cloned_row.html(html);

不要直接调整HTML,使用find()将需要替换的部分更改为需要替换的内容。

关于javascript - jQuery .clone(true, true) 不克隆事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32562749/

相关文章:

javascript - 如何使进度条值根据输入的数字增加

javascript - 如何在不使用 <form> 元素的情况下触发 html5 验证?

javascript - 单击外部时隐藏 div

java - 为什么 CopyOnWriteArrayList 需要写入和读取操作的副本?

linux - 迁移部署在 Linux VM 上的软件?

c# - 什么时候应该提供接口(interface)的通用和非通用版本?

javascript - Array.push 受到 Array.unshift 调用后的影响

javascript - 子类组件来重写事件处理程序?

javascript - 使用 css 和 javascript 的图像 slider

javascript - 两个单独的 HTML 元素上的链接 'active' 状态