JQuery 将类添加到克隆元素
这是我的脚本:
$('.addprop').click(function() {
$('#clone').clone().insertAfter('.addprop');
})
我需要向正在创建的新元素添加一个类。是否可以?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,确实如此:
虽然您是根据
id
、$('#clone')
克隆元素,但请注意,将有两个元素共享 < strong>相同的id
,这使得结果无效HTML,所以我建议:这将有效地添加数字
1
到当前 id 值的末尾。为了使其更加动态,您可能需要将其基于新类名的元素数量的计数:Yes, it is:
Although you're cloning an element based on its
id
,$('#clone')
, so note that there will be two elements sharing the sameid
, which makes the result invalid HTML, so I'd suggest:This will effectively add the number
1
to the end of the end of the currentid
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:当然。
在
.clone()
方法之后,当前元素是克隆。注意
您需要更改克隆的 id ,因为它在 DOM 中必须是唯一的,当你克隆该元素时,id 也会被克隆。
所以最好做类似的事情
Sure.
After the
.clone()
method the current element is the clone..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..So better to do something like