javascript - 为什么我无法从 onclick 属性调用名为clear的函数?

标签 javascript html

我正在尝试创建一个简单的计算器,当单击按钮时,其值显示在文本字段中,并且按钮“C”应该清除文本字段,但其 onclick="clear()"不起作用? ?

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Calculator</title>
        <style>
            #button{
                padding: 10px;
            }
        </style>
        <script>
            function fill(val){
                document.getElementById("field").value+=val;
            }
            function clear(){
                document.getElementById("field").value="";
            }
        </script>
    </head>
    <body>
        <form>
        <table>
            <tr><input type="text" name="field" id="field" size="8"/></tr>
        <%! int k = 1; %>
        <% for(int i=0;i<3;i++){ %>
        <tr> <%
            for(int j=0;j<3;j++){ %>
            <td><input type="button" id="button" onclick="fill(this.value)" value="<%=k++%>" /></td>
          <%  } %>
        </tr>
        <% } %>
        <tr>

<!--here onclick="clear()" is not working?? -->

            <td><input type="button" id="button" value="C" onclick="clear()"/></td>
            <td><input type="button" id="button" value="0" onclick="fill(this.value)"</td>
            <td><input type="submit" id="button" value="="</td>
        </tr>
        </table>
        </form>
    </body>
</html>

最佳答案

内在事件属性(如onclick)很糟糕。他们在内部实现 with :

Use of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues.

因此,您实际上是在调用 document.clear()而不是您的全局 clear()

解决此问题的快速方法是将函数重命名为其他名称或显式调用 window.clear()

更好的解决方案是将事件处理程序与 addEventListener 绑定(bind)而不是内在的事件属性。

enter image description here

关于javascript - 为什么我无法从 onclick 属性调用名为clear的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40665417/

相关文章:

javascript - 将 jQuery (Json) 中的日期时间附加到表中

javascript - 如何将react组件转换为html字符串?

javascript - 元素后的 HTML 脚本标签

javascript - i/info icon : click it to reveal text/can this be done with css, 怎么办?

javascript - "&lt;script src="的相对性

html - CSS 图像网格填充

html - 如何使水平导航栏上的嵌套子菜单垂直?

javascript - 无法在 JavaScript 中访问 JSON 数组的值

javascript - 如何测量脚本的执行时间?

javascript - 单击同一按钮时强制过渡动画