我正在尝试获取输入字段中给定部分所需的成分数量。
当 dom 上的金额发生变化时,我无法访问 html 中的初始金额。因此,我无法获取输入字段中给定部分的准确金额。
function calcAmount() {
let size = document.getElementById('portion').value;
if (size < 1 || size > 5) {
return;
}
let portions = document.querySelectorAll('.span');
for (let i = 0; i < portions.length; i++) {
let amount = parseInt(portions[i].innerText);
let newAmount = amount * size;
let portion = newAmount;
portions[i].innerText = +portion;
portions[i] = '';
}
document.getElementById('portion').value = ' ';
}
<div class="container recipe-portion">
<span>Zutaten für</span>
<div class="portioning">
<input id="portion" type="tex" placeholder="1 bis 5 eingeben" />
<button onclick="calcAmount()" class="btn">Portionen</button>
</div>
</div>
<div class="container recipe-ingredients">
<div class="ingredients">
<p><span class="span">200</span>g Mehl</p>
</div>
<div class="ingredients">
<p><span class="span">200</span>g Zucker</p>
</div>
<div class="ingredients">
<p><span class="span">50</span>g Kakao</p>
</div>
</div>
使用某种调试系统来查看函数运行时发生了什么。您需要以某种方式可视化您的程序。在这里,我对所有变量使用了一个简单的控制台日志命令,但还有更好的方法。并且不要从 html 获取值。将它们保存在某种“真相来源”中,例如物体或其他东西。
function calcAmount() {
let size = document.getElementById('portion').value;
console.log("=========start===========")
console.log("size = " + size)
if (size < 1 || size > 5) {
return;
}
let portions = document.querySelectorAll('.span');
console.log("portions = " + portions)
for (let i = 0; i < portions.length; i++) {
let amount = parseInt(portions[i].innerText);
console.log("amount = " + amount)
let newAmount = amount * size;
console.log("newAmount = " + newAmount)
let portion = newAmount;
console.log("portion = " + portion)
portions[i].innerText = +portion;
console.log("portions[i].innerText = " + portions[i].innerText)
portions[i] = '';
console.log("portions[i] = " + portions[i])
}
document.getElementById('portion').value = ' ';
console.log("('portion').value =" + document.getElementById('portion').value)
console.log("=========end===========")