使用 javascript 克隆 div 的 children
clone div's children using javascript
我多次克隆 div,我还需要更改其内部 children div。 (例如 id_j1、id_j2 等)
我设法克隆了整个 div 并更改了它的 ID,但没有更改 children 的 ID。
javascript
document.getElementById('btn_new_service').onclick = duplicate;
var i =0;
function duplicate() {
var original = document.getElementById('duplicator');
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicator" + ++i; // there can only be one element with an ID}
original.parentNode.appendChild(clone);
如果我在上面的代码中附加下面的代码,那么我会得到 Uncaught TypeError: clone.children is not a function
的错误。
var new_div_ID = 'duplicator-' + i;
var new_service_ID = 'c_service-'+i;
var new_vat_ID = 'vat-'+i;
var new_amount_ID = 'amount-'+i;
var new_vatamount_ID = 'vat_amount-'+i;
clone.children('#c_service').attr('id',new_service_ID);
clone.children('#vat').attr('id',new_vat_ID);
clone.children('#amount').attr('id',new_amount_ID);
clone.children('#vat_amount').attr('id',new_vatamount_ID);
我从 2 个不同的代码片段中提取了它们,它们工作正常,但是当我将它们组合在一起时,它们却没有。任何提示为什么会发生这种情况?
if i append the code below in the above code then i get an error of
Uncaught TypeError: clone.children is not a function.
children 在 vanilla js 中不是 function
,使用 querySelector
代替 setAttribute
成功
clone.querySelector('#c_service').setAttribute('id',new_service_ID);
我多次克隆 div,我还需要更改其内部 children div。 (例如 id_j1、id_j2 等)
我设法克隆了整个 div 并更改了它的 ID,但没有更改 children 的 ID。
javascript
document.getElementById('btn_new_service').onclick = duplicate;
var i =0;
function duplicate() {
var original = document.getElementById('duplicator');
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicator" + ++i; // there can only be one element with an ID}
original.parentNode.appendChild(clone);
如果我在上面的代码中附加下面的代码,那么我会得到 Uncaught TypeError: clone.children is not a function
的错误。
var new_div_ID = 'duplicator-' + i;
var new_service_ID = 'c_service-'+i;
var new_vat_ID = 'vat-'+i;
var new_amount_ID = 'amount-'+i;
var new_vatamount_ID = 'vat_amount-'+i;
clone.children('#c_service').attr('id',new_service_ID);
clone.children('#vat').attr('id',new_vat_ID);
clone.children('#amount').attr('id',new_amount_ID);
clone.children('#vat_amount').attr('id',new_vatamount_ID);
我从 2 个不同的代码片段中提取了它们,它们工作正常,但是当我将它们组合在一起时,它们却没有。任何提示为什么会发生这种情况?
if i append the code below in the above code then i get an error of Uncaught TypeError: clone.children is not a function.
children 在 vanilla js 中不是 function
,使用 querySelector
代替 setAttribute
成功
clone.querySelector('#c_service').setAttribute('id',new_service_ID);