首页 > 解决方案 > HTML onclick 没有运行功能

问题描述

我是 Javascript 的新手,刚刚进入我的网页设计课。我正在开发一个在 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: expected expression, got '}'”,但我看不出问题出在哪里。任何帮助是极大的赞赏!

旁注,我知道有一些奇怪的拼写错误。我的导师来自印度,英语不是很流利。她制作了 HTML 文件供我们使用,我们只需输入 Javascript。

标签: javascripthtml

解决方案


没有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>

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


推荐阅读