Jquery 克隆并更新所有 ID
Jquery Clone and Update All ids
我想使用它的 id
克隆一个 div
,里面有很多元素,它们也有自己的 id
,我想在克隆后更改。
考虑这个 HTML 结构:
<div id='wrapper1'>
<p id='test1'>Hello</p>
<p id='my-awesome-id1'></p>
</div>
我找到了 this on SO 但它只更改了您克隆的主要元素的 id
而不是子元素。
有什么方法可以将所有 1
更新为 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>
您可以使用这样的函数:
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);
});
我想使用它的 id
克隆一个 div
,里面有很多元素,它们也有自己的 id
,我想在克隆后更改。
考虑这个 HTML 结构:
<div id='wrapper1'>
<p id='test1'>Hello</p>
<p id='my-awesome-id1'></p>
</div>
我找到了 this on SO 但它只更改了您克隆的主要元素的 id
而不是子元素。
有什么方法可以将所有 1
更新为 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>
您可以使用这样的函数:
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);
});