正如您在下面的代码中看到的那样,当我命名我的 function 时discount(),该函数在被调用时不会运行。但是,如果我命名它discounts(),它会正常运行。对此有什么解释吗?
<html lang="en">
<head>
<meta charset="UTF-8">
<title>q3</title>
</head>
<body>
<form action="">
<label> Enter Price:</label>
<input type="text" name="price" id="name">
<label>(RM)</label><br><br>
<label>Enter Discount:</label>
<input type="text" name="discount" id="discount">
<label>(%)</label><br><br>
<button onclick="discount()">Get Discount total</button><br><br>
<input type="text" name="discountPrice" id="discountPrice">
<label>(RM)</label>
</form>
<script>
function discount() {
var price = document.getElementById("name").value;
var discount = document.getElementById("discount").value;
var discountPrice = parseFloat(price) * (1 - parseFloat(discount) / 100);
document.getElementById("discountPrice").value = discountPrice;
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您的代码给出了以下错误:
TypeError: discount is not a function
at HTMLButtonElement.onclick (/:14:34)
Run Code Online (Sandbox Code Playgroud)
这样做的原因是您有以下行:
<input type="text" name="discount" id="discount">
Run Code Online (Sandbox Code Playgroud)
因此,当您使用 时onclick=discount(),discount这里的名称指的是<input>元素,而不是discount()函数。您需要为它们使用两个不同的名称来解决问题。
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |