Is it possible to Clone HTML Elements in jQuery with new ID and Name?

后端 未结 4 1585
日久生厌
日久生厌 2020-12-11 01:42

I want to clone one row of a table, but when I clone, the new element\'s name and id will be the same as the element from which it was cloned.

4条回答
  •  再見小時候
    2020-12-11 02:35

    I would pass prop a map of key/value pairs to update these values after cloning:

    $("#selector").clone().prop({ id: "newId", name: "newName"});
    

    Cloned elements don't exist in the DOM until you add them, so you're not going to have to worry about duplicate ids until you do that.

    Example: http://jsfiddle.net/BbpRA/

    Update: In the comment you say you have 20 inputs you need to clone. I would create a function that takes the DOM element and the new id and name. You could even make a small plugin out of it:

    (function($) {
        $.fn.cloneWithProperties = function (properties) {
            return this.clone().prop(properties);
        };
    })(jQuery)
    

    Usage:

    $("#selector").cloneWithProperties({ id: "newId", name: "newName" });
    

提交回复
热议问题