gpt4 book ai didi

javascript - 名为 "clear"的函数未被调用。尝试使用内联 js 调用 "clear()"

转载 作者:行者123 更新时间:2023-11-30 07:39:48 25 4
gpt4 key购买 nike

我无法找出为什么我的函数没有被调用。我将 alert("test") 放在那里只是为了测试函数是否被调用,而事实并非如此。

HTML:

<input type="button" onclick="clear(price,quantity)" value="Clear">

JS:

function clear(price,quantity){
alert("test");
i=0;
if(i<5){

price[i].value = "";
quantity[i].value = "";
i++;
}
}

编辑:这是所有代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Amount Owed</title>
<script type = "text/javascript">
function amount(price, quantity){
sum1 = price[0].value * quantity[0].value;
sum2 = price[1].value * quantity[1].value;
sum3 = price[2].value * quantity[2].value;
sum4 = price[3].value * quantity[3].value;
return sum1 + sum2 + sum3 + sum4;
}
function clear(price,quantity){
alert("test");
i=0;
if(i<5){

price[0].value = "";
quantity[0].value = "";
i++;
}
}
</script>
</head>
<body>
<h1>Amount Owed</h1>
<p>Enter price for first amount and quantity for each item</p>
<form>
<table>
<tr>
<td>PRICE</td>
<td>QUANTITY</td>
</tr>
<tr>
<td><input type="text" name="price" size="6"></td>
<td><input type="text" name="quantity" size="6"></td>
</tr>
<tr>
<td><input type="text" name="price" size="6"></td>
<td><input type="text" name="quantity" size="6"></td>
</tr>
<tr>
<td><input type="text" name="price" size="6"></td>
<td><input type="text" name="quantity" size="6"></td>
</tr>
<tr>
<td><input type="text" name="price" size="6"></td>
<td><input type="text" name="quantity" size="6"></td>
</tr>
</table>
<input type="button" onclick="pay.value = amount(price,quantity)" value="Total">
<input type="button" onclick="clear(price,quantity)" value="Clear">
<p>The total is: <input type="text" id="pay" name="pay"></p>
</form>
</body>
</html>

最佳答案

可能是因为您的 html 中的 clear(price,quantity) 无效。我敢打赌,如果您检查控制台,它会说“价格”不存在。

为了验证,我创建了一个 demo here (click)并在控制台 (f12) 中显示此错误

Uncaught ReferenceError: price is not defined

问题出在内联 js 中使用的名称“clear”!

这是因为“clear”指的是 document.clear 而这根本不是您想要的。这是不使用内联 js 的另一个论点。在这里阅读:Is "clear" a reserved word in Javascript?在这里:https://www.google.com/search?q=Why+is+inline+js+bad%3F

关于javascript - 名为 "clear"的函数未被调用。尝试使用内联 js 调用 "clear()",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20598838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com