【问题标题】:clone div's children using javascript使用 javascript 克隆 div 的孩子
【发布时间】:2017-09-29 09:19:51
【问题描述】:

我多次克隆一个 div,我还需要更改它的内部子 div。 (例如 id_j1、id_j2 等)

我设法克隆了整个 div 并更改了它的 ID,但没有更改孩子的 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 个不同的代码 sn-ps 中提取了它们,它们运行良好,但是当我将它们结合起来时,它们却没有。任何提示为什么会发生这种情况?

【问题讨论】:

  • 它看起来像一个jQuery/DOMApi熔炉......
  • $(clone).children( as Native DOM 元素没有这个功能
  • @Satpal 我也需要更改孩子的 id

标签: javascript jquery html clone


【解决方案1】:

如果我在上面的代码中附加下面的代码,那么我会得到一个错误 未捕获的 TypeError:clone.children 不是函数。

children 在 vanila js 中不是 function,请改用 querySelectorsetAttribute

做起来

clone.querySelector('#c_service').setAttribute('id',new_service_ID);

【讨论】:

  • 谢谢你!这就像一个魅力,所以另一个没有工作,因为它不是内置功能,对吧?我考虑过,但是因为原始示例是声明一个变量克隆并使其等于主 div 并且在它使用 children 更改孩子的 id 之后
  • @noel293 children 不是我在答案中提到的Node 对象的成员方法。这就是您收到该错误的原因。
猜你喜欢
  • 2016-07-25
  • 2012-12-02
  • 2016-10-26
  • 2014-02-21
  • 2014-12-11
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多