用JavaScript来判断是否输入了内容(含定位)
1、首先,新建一个html文档,书写一个form,三个input,代码如下:<html><head&爿讥旌护gt;<script type="text/javascript" src="js/test.js"></script></head><body><form action="#" method="post">姓名<input type="text" name="first" id="first" /><br />年龄<input type="text" name="second" id="second" /><br /><input type="submit" value="send" onclick="check();"/></form></body></html>效果如图:
2、接下来,我们在test.js里面书写chec氯短赤亻k()函数,因为onclick="check();",类锸责氧铼型为submit的input绑定了这个事件,代码:function check(){ var f=document.getElementById("first").value; var s=document.getElementById("second").value; if(f==""){ //如果姓名的输入框为空 alert("姓名不能为空"); document.getElementById("first").focus(); }else{ if(s==""){ //如果年龄的输入框为空 alert("年龄不能为空");document.getElementById("second").focus(); }else{ document.write(f+s); } }}效果如图:
3、alert("年龄不能为空");document.getElementById("second").focus();分析:先弹窗,点击“确定”后,就会聚焦到相应的输入框。