提问人:Henry David 提问时间:9/2/2023 最后编辑:AndyHenry David 更新时间:9/2/2023 访问量:50
在 DOM 上更改 variabe 后,如何在 javascript 中获取 variabe 的初始值?
How can I get the initial value of a variabe in javascript after changing it on the DOM?
问:
我正在尝试获取输入字段中给定部分所需的成分量。
当 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>
答:
0赞
Peristilo peris
9/2/2023
#1
使用某种调试系统来查看函数运行时发生了什么。你需要以某种方式可视化你的程序。在这里,我对所有变量使用了一个简单的控制台日志命令,但有更好的方法。并且不要从 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===========")
评论
1赞
Henry David
9/4/2023
多谢。这很有帮助。我将值保存在一个数组中,并为每个新计算引用数组中的值,它按预期工作。谢谢。
评论
const ingredients = { mehl: 200, zucker: 200, kakao: 50 }
size