【发布时间】:2022-01-17 04:21:17
【问题描述】:
我正在尝试创建一个简单的计算器,当单击按钮时,它的值会显示在文本字段中,并且按钮“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>
【问题讨论】:
-
您遇到了客户端问题。不要向我们展示服务器端代码。获取 HTML 输出。
-
您没有关闭按钮标签。奇怪的语法突出显示应该是一个线索
-
您的 HTML 无效。使用validator.w3.org/nu
-
好吧,据我所知,你的最后两个输入是一场灾难:第一个没有关闭,而第二个没有关闭并且有一个 caotic 值:
value="=",你应该首先解决这些问题。 -
使用不同的 ID。这就是为什么它叫 id。将您的脚本放在正文末端而不是头部。有时您会触发尚未加载(正文)的某些内容。
标签: javascript html