我有三個輸入和三個變數,我的目標是用輸入中的值更改變數值
const inputs = [
document.querySelector(".bill-input"),
document.querySelector(".custom"),
document.querySelector(".people-number"),
];
var bill = 0;
var tip = 0;
var people = 0;
我完成了這樣做
inputs[0].addEventListener("keyup", (e) => {
bill = Number(e.target.value);
});
inputs[1].addEventListener("keyup", (e) => {
tip = Number(e.target.value);
});
inputs[2].addEventListener("keyup", (e) => {
people = Number(e.target.value);
});
我很確定這不是最佳的方法,所以我想問是否有一種方法可以使用 forEach 或任何其他不需要我每次都撰寫的方法。
uj5u.com熱心網友回復:
- 為每個輸入添加一個資料屬性。
- 使用物件而不是n 個變數來維護這些輸入的狀態。
- 有一個處理程式可以根據其 id 更新物件屬性。
// Initialise the values object
const values = { bill: 0, tip: 0, people: 0 };
// Cache the inputs, and add listeners to them
const inputs = document.querySelectorAll('input');
inputs.forEach(input => input.addEventListener('keyup', handleChange));
// Grab the id from the input's dataset, and
// set the values object property to match
// the input value
function handleChange() {
const { id } = this.dataset;
values[id] = this.value;
console.log(JSON.stringify(values));
}
input { display: block; }
Bill<input data-id="bill">
Tip <input data-id="tip">
People <input data-id="people">
附加檔案
- 解構賦值
uj5u.com熱心網友回復:
是的,您可以使用 forEach。我使用一個開關來獲取輸入元素的索引(在輸入常量中)以了解哪些變數更新。
請看下面的片段:
var bill = 0;
var tip = 0;
var people = 0;
const inputs = [
document.querySelector(".bill-input"),
document.querySelector(".custom"),
document.querySelector(".people-number"),
];
inputs.forEach(function(item,index){
item.addEventListener("keyup", (e) => {
const val = Number(e.target.value);
switch(index){
case 0 : bill = val; break;
case 1 : tip = val; break;
case 2 : people = val; break;
}
console.log(bill,tip,people)
});
});
<input value="3" type="number" class="bill-input">
<input value="10" type="number" class="custom">
<input value="100" type="number" class="people-number">
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486084.html
標籤:javascript 数组 变量 前锋 数字
下一篇:從給定的整數中洗掉重復的數字