【发布时间】:2016-10-25 22:10:15
【问题描述】:
我的数学并不出色,我必须承认 :)
基本上我需要创建一个计算器:
1. width
2. length
3. depth
根据这些输入,我需要以 m³ 显示答案。
让事情变得更加棘手,用户可以在 5 个下拉选项之间进行选择:
1. Centimeter
2. Inches
3. Feett
4. Yards
5. Meters
例如,用户可以执行以下操作:
width = 10 centimeters
length = 7 foot
depth = 2 inches
所以我的想法是将所有用户输入转换为毫米以使它们具有相同的类型。求体积的公式为:
length * height * width
所以我想如果我以毫米为单位,我可以将它转换回米。但是,我遇到了问题,并且没有从我的代码中得到正确的答案。逻辑一定是完全错误的(就像我说我的数学并不出色)
这是我的代码:
<tr>
<td>Width</td>
<td><input type="text" id="width"/></td>
<td>
<select id="width-type">
<option value="centimeter">Centimeter</option>
<option value="inches">Inches</option>
<option value="feet">Feet</option>
<option value="yards">Yards</option>
<option value="meters">Meters</option>
</select>
</td>
</tr>
<tr>
<td>Length</td>
<td><input type="text" id="length"/></td>
<td>
<select id="length-type">
<option value="centimeter">Centimeter</option>
<option value="inches">Inches</option>
<option value="feet">Feet</option>
<option value="yards">Yards</option>
<option value="meters">Meters</option>
</select>
</td>
</tr>
<tr>
<td>Depth</td>
<td><input type="text" id="depth"/></td>
<td>
<select id="depth-type">
<option value="centimeter">Centimeter</option>
<option value="inches">Inches</option>
<option value="feet">Feet</option>
<option value="yards">Yards</option>
<option value="meters">Meters</option>
</select>
</td>
</tr>
<tr>
<td>
<button id="calculate">Calculate</button>
</td>
</tr>
<script>
$('#calculate').click(function(){
//These are the amount of mm in each drop down menu type
var array = new Array();
array['centimeter'] = '10';
array['inches'] = '25.4';
array['feet'] = '304.8';
array['yards'] = '914.4';
array['meters'] = '1000';
//Find the width in mm
var widthVal = $('#width').val();
var widthType = $('#width-type').val();
var width = widthVal * array[widthType];
//Find the length in mm
var lengthVal = $('#length').val();
var lengthType = $('#length-type').val();
var length = lengthVal * array[lengthType];
//Find the depth in mm
var depthVal = $('#depth').val();
var depthType = $('#depth-type').val();
var depth = depthVal * array[depthType];
//Find the total volume in mm
var volumeInMillimeters = length * depth * width;
//try to convert it back to meters
var volume = volumeInMillimeters / 1000;
alert(volumeInMillimeters);
alert(volume);
});
</script>
这里还有一个 js fiddle,所以你可以看到它在工作 - https://jsfiddle.net/xk4r8hm2/1/
如果有人可以帮助我做到这一点,请不要只寻找答案,而是寻找与之相关的解释。
谢谢!
【问题讨论】:
-
您已链接到 jsfiddle 的首页。
-
啊哈,我的错 :)。现在改了
标签: javascript jquery math calculator volume