Jquery克隆并更新所有ID

时间:2016-03-16 16:16:18

标签: javascript jquery html clone

我想使用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等等?

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