是否有可能在jQuery中使用新的ID和名称克隆HTML元素? [英] Is it possible to Clone HTML Elements in jQuery with new ID and Name?

查看:152
本文介绍了是否有可能在jQuery中使用新的ID和名称克隆HTML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想克隆表中的一行,但当克隆时,新元素的名称 id 将和它被克隆的元素一样。



我需要的是具有不同的名称 id

解决方案

我会通过 prop 克隆后更新这些值的键/值对映射:

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

在添加元素之前,克隆的元素不存在于DOM中,因此您不打算不得不担心重复 id s,直到您这样做。 a href =http://jsfiddle.net/BbpRA/ =noreferrer> http://jsfiddle.net/BbpRA/

更新:在你说你有20 输入的评论中,你需要克隆。我将创建一个接受DOM元素和新ID和名称的函数。您甚至可以制作一个小插件:

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

用法:

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


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.

What I need is the cloned elements with a different name and id.

解决方案

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" });

这篇关于是否有可能在jQuery中使用新的ID和名称克隆HTML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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