下拉列表更改时调用Javascript函数

时间:2014-04-16 10:15:44

标签: javascript html

我尝试在更改下拉菜单时实现函数调用。我认为我的问题是我在C ++的编程风格中思考得太多了。我已经研究过这个问题,但没有找到任何类似的答案。

我的代码如下:

JS:

<script type="text/javascript">         

        var type = 0;
        var milk = 0;
        var extra = 0;

        settype(t) {
            type = t;
        }

        setmilk(m) {
            milk = m;
        }

        setextra(e) {
            extra = e;
        }

        function calculateCalories() {
            return (type*milk)+extra;
        }
        function reset() {
            type = 0;
            milk = 0;
            extra = 0;
        }
</script>

HTML:

<table border=4 width=800px>
<tr>
<td align=right>
<h2 style="text-align: left"> Your Coffee Drink: </h2>
<input type="text" name="Input" size="35" style="text-align: right"/>
Calories                       
</td>
</tr>

<td>
Calculate the calories of your favorite coffee drink! *
</td>

<td>
Select Type:
    <select id="coffeetypedropdown" onChange="settype(value);">
        <option value="">Select a Drink</option>
        <option value="0">Caffe</option>
        <option value="1">Caffe Latte</option>
        <option value="1">Caffe Macchiato</option>
        <option value="0">Caffe Americano</option>
        <option value=".5">Cappuccino</option>
    </select>
</td>

<td>
Select Type of Milk
    <select id="milkdropdown" onchange="setmilk(value);">
        <option value="">Select Type of Milk</option>
        <option value="80">Nonfat</option>
        <option value="100">1% Milk</option>
        <option value="120">2% Milk</option>
        <option value="150">Whole Milk</option>
        <option value="130">Soy Milk</option>
    </select>

</td>

<td>
Select Extra
    <select id="extradropdown" onchange="setextra(value);">
        <option value="">Select Extra</option>
        <option value="100">Whipped Cream</option>
        <option value="100">Chocolate Syrup</option>
        <option value="50">Caramel Syrup</option>
        <option value="10">Chocolate Powder</option>
        <option value="100">Heavy Cream</option>
    </select>

</td>


<td>
<input type="button" name="clear" VALUE="Clear" OnClick="Calc.Input.value = reset();">
<input type="button" name="Equals"  VALUE="Calculate!" OnClick="Calc.Input.value =    eval(calcCalories();)">
</td>



</td>

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

请在功能名称前添加功能

<script>
    function settype(t) {
       alert(t);
    }
</script>

如果有任何疑虑,请告诉我。 (你想添加&#39; settype&#39;功能全局? - 与全局变量相同)