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

标签 javascript

我无法找出为什么我的函数没有被调用。我将 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/

相关文章:

javascript - 如何从带参数的指令调用 Angular Controller 作用域函数?

javascript - 使用带有 ajax 的 SVG 为 IO 硬件的状态设置动画

javascript - 如何使用 Object.assign() 从其他对象引用基础对象属性

javascript - 理解 javascript 对象与 map

javascript - 什么是匹配 URL 的好正则表达式?

javascript - GXT 不工作

javascript - 从 View 到自定义 Controller 方法的 ASP.Net MVC 复选框值

javascript - db.collection 不是函数 (MongoDB 3+)

javascript - 基于另一个数组对数组进行排序(更改对象的顺序)

javascript - 使用 JavaScript 从 XML 文件搜索并输出数据