名为“;清除“;没有被呼叫.尝试呼叫“;clear()”;使用内联js

Function named "clear" is not being called. Trying to call "clear()" with inline js

本文关键字:呼叫 js 清除 名为 clear      更新时间:2023-09-26

我不知道为什么我的函数没有被调用。我把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)无效。我敢打赌,如果你检查一下你的主机,它会说"价格"不存在。

为了验证,我在这里创建了一个演示(点击),它在控制台(f12)中显示了这个错误

未捕获引用错误:价格未定义

问题在于内联js中使用的名称"clear"

这是因为"clear"指的是document.clear,而这根本不是你想要的。这是不使用内联js的另一个参数。阅读此处:是";清除";Javascript中的保留字?在这里:https://www.google.com/search?q=Why+是+inline+js+坏的%3F

在这个函数中--onclick="clear(price,quantity)"-pricequantity是尚未定义的变量,因此在调用clear之前会得到一个引用错误。

您可以使用window.price = 1;或(在相同或更宽的范围内)var price = 1来定义它们。后者通常是更好的选择。


看起来您想要传递输入元素的NodeList。你不能仅仅将它们作为全局引用,你必须通过DOM来访问它们。

由于您正在处理表单控件上的单击事件处理程序,因此可以通过this访问该表单控件。表单控件元素对象具有引用其关联表单的form属性。表单元素对象具有elements集合。元素集合允许您按名称访问表单控件。如果有多个控件具有相同的名称,则会得到NodeList,而不是节点本身。

onclick="clear(this.form.elements.price,this.form.elements.quantity)"