我是 JavaScript 新手,我试图在单击选择标签时显示该单元。我使用了 Switch 语句,但它没有做任何事情。
HTML:
<select class="unit_from">
<option value = "Kilogram">Kilogram</option>
</select>
<select id="unit_to" onchange="convert()">
<option value = "Metric_ton">Metric ton</option>
<option value = "Kilogram">Kilogram</option>
<option value = "Gram">Gram</option>
<option value = "Milligram">Miligram</option>
<option value = "Mcg">Mcg</option>
<option value = "Long_ton">Long ton</option>
<option value = "Stone">Stone</option>
<option value = "Pound">Pound</option>
<option value = "Ounce">Ounce</option>
</select>
</div>
<div class="text_input">
<input id="txtValue" type="text" />
<p id="print_ans"></p>
选择选项值时,单位将显示在 id=print_ans 段落中。
Javascript:
<script>
function convert()
{
var kilo = document.getElementById("txtValue").value;
var get_unit = convert_unit();
}
function convert_unit()
{
var x;
var y = document.getElementById("unit_to").value;
switch(y)
{
case Metric_ton:
x = kilo * 0.001;
break;
case Kilogram:
x = kilo * 1;
break;
case Gram:
x = kilo * 1000;
break;
case Milligram:
x = kilo *0.000001;
break;
case Mcg:
x = kilo * 0.000000001;
break;
case Long_ton:
x = kilo * 0.000984207;
break;
case Stone:
x = kilo * 0.00110231;
break;
case Pound:
x = kilo * 0.157473;
break;
case Ounce:
x= kilo * 2.20462;
break;
}
document.getElementById("print_ans").innerHTML = x;
}
示例:http: //jsfiddle.net/6Gtcd/4/