我创建了一些放入类 .card 中的代码,以及克隆该卡的 JavaScript 函数。 卡内部还有另一个执行简单计算的功能。当我克隆该卡时,就会出现问题,因为第一个卡工作正常,但其他卡根本不执行任何计算。 我注意到的另一个问题是第一张卡上的字段值......好吧,这些值也被克隆,但目的是制作一个相当空的字段新卡。
<div id="card" class="card">
<!-- And here comes all the card contets -->
</div>
<!-- And here is suposed to hold the new content with no filled fiels but with calcutations woking -->
<div id="clone"></div>
//this is supposed to clone the fist card
function add_card(){
var theCard = document.getElementById('card'); //takes the HTML id leftSide to the theLeftSide var
var cardClone = theCard.cloneNode(true);//cloning (float)
clone.appendChild(cardClone);//cloning (paste)
}
//And this should be doing some simple calcs
function calc_item(){
var val_preco = document.getElementById('preco').value;
var val_peso = document.getElementById('peso').value;
var relacao_preco = val_preco / val_peso;
document.getElementById('preco_grama').innerHTML = (relacao_preco);
}
那么...我做错了什么?
最佳答案
第一个问题是您不能在页面中重复 ID...根据定义它们是唯一的
您可以使用document.querySelector(cssSelector)
获取页面中的第一个匹配项。在这种情况下可以使用类“card”作为选择器
接下来我存储了一个初始克隆。然后每次需要新的时克隆它。然后就可以根据需要修改克隆的内容了。
计算时使用document.querySelectorAll()
获取要迭代的元素集合。不知道你的计算结果是多少,我只是将所有卡片中的所有数字相加以显示其工作原理
var cardCount = 1
// store a clone right away
var storedClone = document.querySelector('.card').cloneNode(true);
function add_card() {
//clone the original clone
var cardClone = storedClone.cloneNode(true); //cloning (float)
//update content of clone
cardClone.textContent = 'Card ' + (++cardCount);
clone.appendChild(cardClone); //cloning (paste)
}
function calc_item() {
var total = 0;
var cards = document.querySelectorAll('.card');
cards.forEach(function(el) {
total += +/\d+/.exec(el.textContent);
});
document.getElementById('total').innerHTML = 'Card total = ' + total;
}
#clone {
border: 2px solid #ccc
}
<button onclick="add_card()">Add card</button> <button onclick="calc_item()">Calc</button>
<div id="total">Card total = 1</div>
<!-- And here is suposed to hold the new content with no filled fiels but with calcutations woking -->
<div id="clone">
<div class="card">
Card 1
</div>
</div>
关于javascript - 如何克隆 DOM 结构,以及如何在克隆上进行 JavaScript 计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47522853/