0
我是JavaScript新手,我試圖在單擊選擇標籤時顯示單位。我使用了Switch語句,但它沒有做任何事情。Javascript onchange選項值
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/
使用jQuery!你不會後悔的 – Lance