HTML和JavaScript代码审查

时间:2014-12-04 22:58:26

标签: javascript html function

查看我的代码我在功能total_Cost()时没有得到结果被称为我不明白为什么这发生在我身上。



function total_Cost()
{
    var x = document.getElemenById('1');
    var y = document.getElemenById('2');
    var z = document.getElemenById('3');
    var s = document.getElemenById('cost');
    s.value = (x.value * 3.49) + (y.value * 3.60) + (z.value * 4.49);
}

<body>
    <h2>Coffee Order Form</h2>
    <form method='get'>
        <table border="1" cellpadding='0px' cellspacing='0px'>
            <tr><th>Product Name </th><th>Price</th><th>Quantity</th></tr>
            <tr><td>French Vanilla (1 lb)</td><td>$3.49</td><td><input type = "text" size='5'id='1' value=''></td></tr>
            <tr><td>Hazelnut Cream (1 lb)</td><td>$3.60</td><td><input type = "text" size='5'id='2' value=''></td></tr>
            <tr><td align='centre'>Colombian (1 lb)</td><td>$4.49</td><td><input type = "text" size='5' id='3' value=''></td></tr>
        </table>
        <br>
        <input type='button' Value='Total Cost' id='total' onclick='return total_Cost();'> &nbsp;<input type = "text" size='10' id='cost' value=''>
        <br>
        <br>
        <input type='submit' Value='Submit Order'> &nbsp; <input type='submit' Value='Clear Order Form'>
    </form>
</body>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

除了一些拼写错误之外,主要问题是你不需要从你的onclick功能返回。

但是,我建议你在这种情况下使用事件监听器以避免混淆。

&#13;
&#13;
function total_Cost() {
    var x = document.getElementById('1');
    var y = document.getElementById('2');
    var z = document.getElementById('3');
    var s = document.getElementById('cost');
    s.value = (x.value * 3.49) + (y.value * 3.60) + (z.value * 4.49);
}
&#13;
<body>
    <h2>Coffee Order Form</h2>
    <form method='get'>
        <table border="1" cellpadding='0px' cellspacing='0px'>
            <tr><th>Product Name </th><th>Price</th><th>Quantity</th></tr>
            <tr><td>French Vanilla (1 lb)</td><td>$3.49</td><td><input type = "text" size='5'id='1' value=''></td></tr>
            <tr><td>Hazelnut Cream (1 lb)</td><td>$3.60</td><td><input type = "text" size='5'id='2' value=''></td></tr>
            <tr><td align='centre'>Colombian (1 lb)</td><td>$4.49</td><td><input type = "text" size='5' id='3' value=''></td></tr>
        </table>
        <br>
        <input type='button' Value='Total Cost' id='total' onclick='total_Cost();'> &nbsp;<input type = "text" size='10' id='cost' value=''>
        <br>
        <br>
        <input type='submit' Value='Submit Order'> &nbsp; <input type='submit' Value='Clear Order Form'>
    </form>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<script>
    function total_Cost()
    {
        var x=document.getElementById('1');
        var y=document.getElementById('2');
        var z=document.getElementById('3');
        var s=document.getElementById('cost');
        s.value=(x.value * 3.49) +(y.value * 3.60) + (z.value * 4.49);
    }
</script>

你忘了元素中的那个。