JavaScript不起作用,求解释?
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>无标题文档</title><script type="text/javascript"> var userName = document.getElementById("userName"); var password = document.getElementById("password"); function check() { if(userName.value == "") { alert("用户名不能为空!"); return false; } if(password.value == "") { alert("密码不能为空"); return false; } if(userName.value.length<4||userName.length>10) { alert("用户名长度要在4到10之间"); return false; } if(password.value.length<4||password.length>10) { alert("密码长度要在4到10之间"); return false; } return true; } </script></head><body><form action="#" method="post" onsubmit="return check()"> 用户名: <input type="text" name="userName" id="userName" /> <br /> 密 码: <input type="password" name="password" id="password" /> <br /> 性 别: <input type="radio" name="sex" value="1" /> 男 <input type="radio" name="sex" value="0" /> 女<br /> 兴 趣: 足球 <input type="checkbox" name="checkbox" value="0" /> 篮球 <input type="checkbox" name="checkbox" value="1" /> 排球 <input type="checkbox" name="checkbox" value="2" /> 羽毛球 <input type="checkbox" name="checkbox" value="3" /> <br /> 地 址: <select name="select"> <option value="0" selected="selected">北京</option> <option value="1">上海</option> <option value="3">陕西</option> </select><br /> <input type="submit" value="点击确认" name="button1" /> <input type="reset" value="重置" name="button2" /> </form></body></html>
var userName = document.getElementById("userName"); var password = document.getElementById("password");
------解决方案--------------------
<script type="text/javascript" src="/*.js">
[解决办法]
因为在加载脚本的时候,HTML 的 DOM 还没加载完,所以这段脚本是取不到 DOM 对象的。
解决方法:
1:把 script 整体搬到 body 的后面
2:把 script 中的代码放到 window.onload = function() { } 函数体中
[解决办法]
var userName = document.getElementById("userName");
var password = document.getElementById("password");
要放在你验证表单的function内 才能动态获得你当时的值
否则永远是页面初始化时候你的表单的值
[解决办法]