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

jQuery .clone(true, true) not cloning events

我正在编写这段代码,但由于我不太擅长 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;
};

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

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

感谢您的帮助!

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

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

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