我有一个关于命名函数的问题。正如您在下面的代码中所见,当我将函数命名为 discount() 时,该函数在调用时将不起作用。但是,如果我命名 if 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>
您的代码给出了以下错误:
TypeError: discount is not a function
at HTMLButtonElement.onclick (/:14:34)
这样做的原因是您有以下行:
<input type="text" name="discount" id="discount">
因此,当您使用 时onclick=discount()
,discount
这里的名称指的是<input>
元素,而不是discount()
函数。您需要为它们使用两个不同的名称来解决问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句