【发布时间】:2021-03-30 20:52:12
【问题描述】:
您好,我正在尝试构建 BAC(身体酒精含量)计算器。 除了具有 3 个选择的“酒精类型”之外,所有按钮都是用户单独输入的。查看下面的 HTML。
<div class="main-container">
<div class="viewport">
<div class="gender-buttons" id="gender-buttons">
<button class="male-button">MALE</button>
<button class="female-button">FEMALE</button>
</div>
<div class="weight-input" >
<h3>ENTER WEIGHT</h3>
<input id="weight-input" type="number" placeholder="75kg" required>
</div>
<div class="alcohol-content" >
<h3>I'VE HAD</h3>
<input id="alcohol-content" type="number" placeholder="5" required>
</div>
<div class="alcohol-type">
<h3>OF</h3>
<select name="type-of-alcohol" id="alcohol-type">
<option value="1.5">Shots of Spirits</option>
<option value="5">Glasses of Wine</option>
<option value="12">Pints of Beer</option>
</select>
</div>
<div class="submit-button" >
<input type="submit" id="submit-button">
</div>
<div class="result-container" id="result-container">
</div>
</div>
</div>
这是我的 JS 代码。
//输入
let weightElement = document.getElementById("weight-input"); // User enters weight
let amountElement = document.getElementById("alcohol-content") // Number of drinks consumed
let submitButton = document.getElementById("submit-button") // Submits calculation
const alcoholTypeElement = document.getElementById("alcohol-type") // Type of alcohol consumed with ounces as measurement of value
//计算BAC的函数
submitButton.addEventListener('click', function(){ // User clicks Submit button will start the calculation
const weight = parseInt(weightElement.value); // Weight will be the integer value of the weightElement input
const amount = parseInt(amountElement.value); // Amount will be the integer value of amountElement input
const alcoholType = parseInt(alcoholTypeElement.value); // AlcoholType will be the integer value of alcoholTypeElement
const gramsOfAlcohol = (alcoholType*amount)*14; // 14 is the standard multipler for US/UK for grams of alcohol/ per standard unit
const genderMultiplyer = 0.55;
const bloodAlcoholContent = (gramsOfAlcohol / ((weight * 1000) * genderMultiplyer))*100
document.getElementById("result-container").innerHTML =
bloodAlcoholContent.toFixed(2);})
如您所见,所有元素都已链接到它们各自的 JS 变量。现在“酒精类型”有 3 个选择,烈酒、葡萄酒和啤酒。每个人都有自己的价值观。我正在尝试将“值”作为条件合并到我的函数中。
我尝试创建一个如下所示的 switch 语句来反映其酒精量的值(例如,Spirits 是 40% 酒精,标准单位是 1.5 盎司,并且在上面的变量中(constgramOfAlcohol = (alcoholType*amount )*14;其中 14 是计算每盎司酒精克数的标准乘数:
const alcoholTypeValue = (alcoholType) => {
switch(value){
case 12:
return value * 0.05 // 0.05 = 5% Alcohol (Beers)
break
case 5:
return value * 0.12 // 0.12 = 5% Alcohol (Wine)
break
case 1.5:
return value * 0.4 // 0.40 = 5% Alcohol (Spirits)
break
}
}
因此,如果用户选择烈酒,那么我们知道标准酒精含量为 40% 的烈酒(1.5 盎司)乘以 14 将得到 8.4 克纯酒精。
因此,如果用户选择葡萄酒,那么我们知道标准杯(5 盎司)12% 酒精的葡萄酒乘以 14 将得到 8.4 克纯酒精。
因此,如果用户选择啤酒,那么我们知道标准品脱(12 盎司)5% 酒精的烈酒乘以 14 将得到 8.4 克纯酒精。
我希望这会有所帮助,我似乎找不到针对我的问题的具体问题,但本质上,我最终使用的选择需要在用于我的函数之前进行预先计算。
谢谢
【问题讨论】:
-
有什么问题?您描述了您的解决方案,但究竟是什么不起作用?
标签: javascript html if-statement switch-statement