Javascript onchange选项值

时间:2013-09-28 01:07:27

标签: javascript

我是JavaScript新手,我在点击select标签时试图显示该单元。我使用了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/

1 个答案:

答案 0 :(得分:0)

你有几个错误:

在您的switch语句中,您使用case Metric_ton:之类的内容但Metric_ton应该是字符串,而不是变量,所以应该写成case 'Metric_ton':

同样,kilo未在函数convert_unit中分配值,它超出了该函数的范围,因此您需要这样的内容:

http://jsfiddle.net/6Gtcd/9/

其中为kilo分配了convert_unit内的值。事实上,我将convert_unit重命名为convert并删除了原始convert函数,因为它似乎没必要。