使用Javascript切换单位转换语句。
答案 0 :(得分:0)
You tried to use "unit" as js variable which is already part of loaded document, need to correct your code as below,
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<input id="units" type="number" placeholder="Feet" value="1"/>
<script>
var unit = document.getElementById("units").value;
switch (unit) {
case 0:
unit = valNum/3.2808;
break;
case 1:
unit = valNum / 0.0022046;
break;
document.getElementById("demo").innerHTML = "Today is " + unit;
</script>
</body>
</html>
Again, need to write separate function to load values from input field to screen. it could be event based like keypressed, mouse or simple button.
答案 1 :(得分:0)
以下是您的代码中的一些问题:
valNum
case 1:
switch-case
中的语法错误。
function calc() {
var unit = parseInt(document.getElementById("unit").value, 10) || -1;
var feet = parseInt(document.getElementById("feet").value, 10) || 0;
var result = 0;
switch (unit) {
case 0:
result = 'Result is: ' + (feet / 3.2808);
break;
case 1:
result = 'Result is: ' + (feet / 0.0022046);
break;
default:
result = 'Unit ##.##';
break;
}
document.getElementById("demo").innerHTML = result;
}
<p id="demo">Unit ##.##</p>
<input placeholder="Unit" oninput='calc()' id='unit' />
<input placeholder="Feet" oninput='calc()' id='feet' />