JQuery 将类添加到克隆元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8720432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery adding class to cloned element
提问by Tomarz
This is my script:
这是我的脚本:
$('.addprop').click(function() {
$('#clone').clone().insertAfter('.addprop');
})
I need to add a class to the new element that is being created. Is it possible?
我需要向正在创建的新元素添加一个类。是否可以?
回答by David says reinstate Monica
Yes, it is:
是的:
$('.addprop').click(function() {
$('#clone').clone().addClass('newClass').insertAfter('.addprop');
})
Although you're cloning an element based on its id
, $('#clone')
, so note that there will be two elements sharing the same id
, which makes the result invalid HTML, so I'd suggest:
尽管您是根据其id
,克隆一个元素$('#clone')
,但请注意,将有两个元素共享相同的id
,这会使结果无效的 HTML,因此我建议:
$('.addprop').click(function() {
$('#clone').clone().attr('id',id += 1).addClass('newClass').insertAfter('.addprop');
});
This will effectively add the number 1
to the end of the end of the current id
value. To make this more dynamic you'd probably need to base it on a count of the number of elements of the new class-name:
这将有效地将数字添加1
到当前id
值的末尾。为了使其更具动态性,您可能需要根据新类名的元素数量进行计数:
$('.addprop').click(function() {
$('#clone').clone().attr('id',id += $('.newClass').length).addClass('newClass').insertAfter('.addprop');
});
回答by Gabriele Petrioli
Sure.
当然。
After the .clone()
method the currentelement is the clone..
在.clone()
方法之后,当前元素是克隆..
$('#clone').clone().addClass('class-name-here').insertAfter('.addprop');
Notice
注意
you will need to change the id
of the clone as it must be unique in the DOM and when you clone that element, the id is cloned as well..
您将需要更改id
克隆的 ,因为它在 DOM 中必须是唯一的,并且当您克隆该元素时,ID 也会被克隆。
So better to do something like
所以最好做类似的事情
$('#clone').clone().attr('id','newid').addClass('class-name-here').insertAfter('.addprop');