HTML onclick未运行功能

时间:2018-12-10 00:07:50

标签: javascript html

我是Java的新手,只是开始参加我的网页设计课程。我正在用HTML内的Javascript开发项目。我已经全部写好了,但是HTML似乎没有调用Javascript函数。我一直在寻找解决方案,但似乎无法解决任何问题。代码是:

<html>
<head>
<script>
var calculateInterest = function(){
var rate;
var total;
var years = document.getElementById("years").value;
var principleAmount = document.getElementById("principal").value;
var interestRate = document.getElementById("intrest").value;
    if ((interestRate >= 0) && (interestRate <= 15)) {
        rate = interestRate / 100;

        if ((principleAmount >= 0) && (principleAmount <= 10000)) {
            total = principleAmount * (1 + rate * years);
            document.getElementById("total_with_intrest").value = total;
        }
        else {
            message-box ("Invalid data for principle amount.");
        }
    }
    else {
        message-box ("Invalid data for interest rate.");
    }
}
</script>
<style>
form{ border: solid blue;
       width:40em;
        padding:0.5em;}
input{padding: 0.5em;}

</style>
</head>


<body>
<form>

Enter Principal Ammount : <input type="text" id ="principal"  />
</br>

Enter Intrest Rate : <input type="text" id ="intrest"    />
</br>
Enter Number of Years : <input type="text" id ="years"  />
</br>
Grand Ammount : <input type="text" id ="total_with_intrest"   disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick=calculateInterest()/> </br>


</form>
</body>

</html>

浏览器错误是第2行上的“ SyntaxError:期望的表达式,得到'}'“,但我只是看不出问题出在哪里。任何帮助将不胜感激!

旁注,我知道有些奇怪的拼写错误。我的老师是印度人,英语不太流利。她制作了HTML文件供我们使用,我们只需要放入Javascript。

1 个答案:

答案 0 :(得分:3)

没有message-box功能。您是说alert()吗?当前,您的代码可以进行以下更改:

var calculateInterest = function(){
    var rate;
    var total;
    var years = document.getElementById("years").value;
    var principleAmount = document.getElementById("principal").value;
    var interestRate = document.getElementById("intrest").value;
    if ((interestRate >= 0) && (interestRate <= 15)) {
        rate = interestRate / 100;

        if ((principleAmount >= 0) && (principleAmount <= 10000)) {
            total = principleAmount * (1 + rate * years);
            document.getElementById("total_with_intrest").value = total;
        }
        else {
            alert("Invalid data for principle amount.");
        }
    }
    else {
        alert("Invalid data for interest rate.");
    }
}
form{ border: solid blue;
       width:40em;
        padding:0.5em;}
input{padding: 0.5em;}
<form>

Enter Principal Amount : <input type="text" id ="principal"  />
</br>

Enter Interest Rate : <input type="text" id ="intrest"    />
</br>
Enter Number of Years : <input type="text" id ="years"  />
</br>
Grand Amount : <input type="text" id ="total_with_intrest"   disabled /></br>
</br>
<input type="button" id="click" value="Calculate" onclick="calculateInterest()" /> </br>


</form>

小型Nitpick:修复了一些与代码无关的小错字。金额=>金额。兴趣=>兴趣。