[英]How to change javascript calculator code?
我用基本的javascript知識制作了這個計算器: https : //jsfiddle.net/7vmtuzsL/4/
此結構中列出了特定食物的參數:
<option value="110,1.24,0,23.09">Chicken breast</option>
<option value="18,0.2,3.92,0.88">Tomato</option>
<option value="374,1.04,80.43,8.11">Rice</option>
我怎樣才能改變這種風格以獲得更有條理和透明的結構?
例如,110 是卡路里,0.2 是脂肪,3.92 是碳水化合物,0.88 是蛋白質。
我想為所有維生素和礦物質等食物添加 20 個參數。 我發現這些結構不好,因為你很容易出錯,不知道哪個參數屬於哪個類別。
任何想法如何在不重建整個代碼的情況下命名每個值?
然后你可以有一個對象數組(食物數組)並且每個對象(食物)都有它的屬性:
arrayOfFood = [
apple: {
cal: 20,
fat: 0.2
},
pear: {
cal: 25,
fat: 0.3
}
]
您可以使用如下所示的對象:
nutritionValue = {
cal: [110, 18, 374, ...],
fats: [0.2, ....],
carbs: [3.92, ....],
proteins: [0.88, ....],
vitamins: [....],
minerals: [....]
}
您可以使用數據屬性,例如
<option data-calories="110" data-fats="0.2" data-carbs="3.92" data-proteints="0.88" value="chicken breast">Chicken breast</option>
要獲取選定的選項數據,請使用以下命令:
console.log($('select > option:selected').data())
使用data 屬性在 HTML 標簽上插入邏輯數據。
我使用getAttribute
處理它們的舊方法,但如果您知道您的用戶平台是現代的,則可以使用數據集方法。
var foodSelector = document.getElementById('food-selector'); function getFoodData(option) { var info = { calories: parseFloat(option.getAttribute('data-calories')), fats: parseFloat(option.getAttribute('data-fats')), carbs: parseFloat(option.getAttribute('data-carbs')), proteins: parseFloat(option.getAttribute('data-proteins')) }; return info; } foodSelector.addEventListener('change', function(evt) { var info = getFoodData(evt.target.options[evt.target.selectedIndex]); console.log(info) })
<select id="food-selector"> <option data-calories="110" data-fats="1.24" data-carbs="0" data-proteins="23.09">Chicken breast</option> <option data-calories="18" data-fats="0.2" data-carbs="3.92" data-proteins="0.88">Tomato</option> <option data-calories="374" data-fats="1.04" data-carbs="80.43" data-proteins="8.11">Rice</option> </select>
回應評論:
關注點分離很有價值,但您並不總是對代碼進行那種控制。 也許您需要 CSS 的屬性,或者您可能從某個外部來源獲得它。
無論如何,下面是一個片段,展示了如何將數據保存在 JavaScript 中,並且只在網站中包含最低要求的 HTML:
//Find existing elements var foodSelector = document.getElementById("food-selector"); //Data var data = [{ calories: 110, fats: 1.24, carbs: 0, proteins: 23.09, name: "Chicken breast", node: document.createElement("option") }, { calories: 1120, fats: 124, carbs: 10, proteins: 2.19, name: "Tomato", node: document.createElement("option") }, { calories: 180, fats: 1.84, carbs: 19, proteins: 9.09, name: "Rice", node: document.createElement("option") }, ]; //Append nodes data.forEach(function(dataPoint) { dataPoint.node.textContent = dataPoint.name; foodSelector.appendChild(dataPoint.node); }); //Listen for event foodSelector.addEventListener("change", function(evt) { var dataPoint = data.find(function(d) { return d.node === foodSelector.options[foodSelector.selectedIndex]; }); console.log(dataPoint); });
<select id="food-selector"></select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.