0

我正在尝试制作自己的clone功能,但遇到了问题。我可以自己使用 jQuery 的clone函数而不会出现这样的问题:`

$.prototype.cloneDumpingEvents = function () {
    return $(this).clone();
};

(或者,在行动中看到它:http: //jsfiddle.net/Shawn/dCm59/2/

但是,如果我尝试使其适用于元素集合(添加each),它将删除原始:

$.prototype.cloneDumpingEvents = function () {
    return this.each(function() {
        $(this).clone();
    });
};

(或者,在行动中看到它:http: //jsfiddle.net/Shawn/dCm59/3/

为什么第二个版本删除了原版?

4

1 回答 1

2

因为您要返回原件而不是克隆。改用这个:

$.fn.cloneDumpingEvents = function () {

    var collection = $();

    this.each(function() {
        collection = collection.add( $(this).clone() );
    });

    return collection;
};

这是你的小提琴:http: //jsfiddle.net/dCm59/4/


正如@FabrícioMatté 在评论中指出的那样,.map要短得多:

$.fn.cloneDumpingEvents = function () {
    return this.map(function() {
        return $.clone(this);
    });
};

这是你的小提琴:http: //jsfiddle.net/dCm59/7/

于 2013-02-15T16:05:29.690 回答