这就是我所拥有的:
HTML
<div class="table-product-wrap-inner">
<table class="table-product">
<a href="#1" data-toggle="collapse"></a>
</table>
<button class="btn-copy-group"></button>
<div class="collapse" id="1"></div>
<table class="table-product">
<a href="#2" data-toggle="collapse"></a>
</table>
<div class="collapse" id="2"></div>
<table class="table-product">
<a href="#3" data-toggle="collapse"></a>
</table>
<div class="collapse" id="3"></div>
</div>
jQuery
init: function () {
var that = this;
this.$productEdit..on('click', '.btn-copy-group', function(){
var $targetTable = $(this).closest('.table-product-wrap-inner'),
$clonedTable = $targetTable.clone(),
$clonTableId = $clonedTable.removeAttr('data-product-link-group-id'),
$groupName = $clonedTable.find('.product-group-link-name'),
$linkName = $clonedTable.find('.product-link-title'),
$idLink = $clonedTable.find('.product-link-id');
$targetTable.after($clonTableId);
$groupName.val($groupName.val() + " Копия");
$linkName.val($linkName.val() + " Копия");
$idLink.val('');
})
}
点击button
与类 .btn-copy-group
我重复 div
与类 .table-product-wrap-inner
在原来的情况下,但我还需要分配 uniqeu id
同样href
对于 table
中的每对链接和 div
旁边。
对于唯一 ID,我有一个函数:
getUniqueId: (function () {
var i = 1;
function getUniqueId() {
return i += 1;
}
return getUniqueId;
}())
我用它来分配 inique id
当我克隆一对 table
+ div
:
var newId = 'copy' + that.getUniqueId();
$clonedTable.after($targetDiv.clone().attr('id', newId));
$clonedTable.find('[data-toggle=collapse]').attr('href', '#' + newId);
所以我不知道当我们有很多对时如何使用它(可能有不同数量的对)table
+ div
.
最终结果(复制后)应该是这样的:
<div class="table-product-wrap-inner">
<table class="table-product">
<a href="#1" data-toggle="collapse"></a>
</table>
<button class="btn-copy-group"></button>
<div class="collapse" id="1"></div>
<table class="table-product">
<a href="#2" data-toggle="collapse"></a>
</table>
<div class="collapse" id="2"></div>
<table class="table-product">
<a href="#3" data-toggle="collapse"></a>
</table>
<div class="collapse" id="3"></div>
</div>
<!-- COPY -->
<div class="table-product-wrap-inner">
<table class="table-product">
<a href="#copy1" data-toggle="collapse"></a>
</table>
<button class="btn-copy-group"></button>
<div class="collapse" id="copy1"></div>
<table class="table-product">
<a href="#copy2" data-toggle="collapse"></a>
</table>
<div class="collapse" id="copy2"></div>
<table class="table-product">
<a href="#copy3" data-toggle="collapse"></a>
</table>
<div class="collapse" id="copy3"></div>
</div>
如果用户点击 <button class="btn-copy-group">
重复<div class="table-product-wrap-inner">
他会得到另一份独特的 id
等等等等
最佳答案
您可以创建一个唯一的 ID:
function uniqueID() {
return "id-" + Date.now();
}
var id = uniqueID();
console.log(id);
Date.now() 方法返回自 1970 年 1 月 1 日 00:00:00 以来经过的毫秒数。即使您一次克隆超过 1 个元素,这也应该为您提供一个相当节省的唯一 ID。
关于javascript - 如何将唯一的 id 和 href 分配给一对克隆对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40384323/