我想使用div
克隆一个id
,其中包含许多元素,这些元素也有自己的id
我想在克隆后更改。
考虑这个HTML结构:
<div id='wrapper1'>
<p id='test1'>Hello</p>
<p id='my-awesome-id1'></p>
</div>
我找到了this on SO,但它只更改了您克隆的主要元素的id
,而不是子项。
有没有办法让我可以将所有1
更新为2
等等?
答案 0 :(得分:2)
这样做会创建一个像:
这样的克隆<div id="wrapper2">
<p id="test2">Hello</p>
<p id="my-awesome-id2"></p>
</div>
$('div').clone().filter(function() {
$(this).prop('id', $(this).prop('id').replace('1', '2')).children().filter(function() {
return $(this).prop('id', $(this).prop('id').replace('1', '2'))
});
return $(this)
}).appendTo('body')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='wrapper1'>
<p id='test1'>Hello</p>
<p id='my-awesome-id1'></p>
</div>
答案 1 :(得分:0)
您可以使用以下功能:
function changeIdNumberOnElementAndChildren(element, newIdNumber) {
var $element = $(element),
$elementChildren = $element.children(),
oldId = $element.attr("id"),
newId = (oldId) ? oldId.replace(/\d+$/, newIdNumber) : null;
if (newId) {
$element.attr("id", newId);
}
if ($elementChildren.length > 0) { // recursively call function on children
$elementChildren.each(function(i, child) {
changeIdNumberOnElementAndChildren(child, newIdNumber);
});
}
}
然后只需在克隆上调用它来更改ID:
$(function() {
var clone = $("#wrapper1").clone();
// below changes the ids so that they end in 559 rather than 1
// (i.e. "wrapper559", "test559" and "my-awesome-id559")
changeIdNumberOnElementAndChildren(clone, 559);
});