我正在尝试创建一个简单的计算器,当单击一个按钮时,它的值显示在文本字段中,按钮"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>
Run Code Online (Sandbox Code Playgroud)
Que*_*tin 12
内在事件属性(如onclick)是可怕的.他们在内部实施with:
建议不要使用with语句,因为它可能是混淆错误和兼容性问题的根源.
因此,您实际上是在调用document.clear()而不是全局调用clear().
对此的快速解决方法是将函数重命名为其他内容或显式调用window.clear().
更好的解决方案是绑定事件处理程序addEventListener而不是内部事件属性.
| 归档时间: |
|
| 查看次数: |
845 次 |
| 最近记录: |