0

我是 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/

4

1 回答 1

0

你有几个错误:

在您的switch陈述中,您使用诸如case Metric_ton:Metric_ton应该是字符串而不是变量之类的东西,因此应该编写case 'Metric_ton':

另外,kilo没有在函数中赋值convert_unit,它超出了该函数的范围,所以你需要这样的东西:

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

其中在kilo内分配了一个值convert_unit。事实上,我重命名convert_unitconvert删除了原始convert功能,因为它似乎没有必要。

于 2013-09-28T01:37:02.020 回答