示例 1 :
练习-删除行为前的提示
在进行删除操作前,都应该提示用户是否要删除
<script> function deleteRow(link){ var b = confirm("确定删除?") if(!b) return; var table = document.getElementById("heroTable"); var td = link.parentNode; var tr = td.parentNode; var index=tr.rowIndex; table.deleteRow(index); } </script> <table width="100%" border = "1" cellspacing="0" id="heroTable"> <tr > <td width="50%">英雄名称</td> <td> 操作 </td> </tr> <tr > <td>盖伦</td> <td> <a href="#" onclick="deleteRow(this)">删除</a> </td> </tr> <tr > <td>提莫</td> <td> <a href="#" onclick="deleteRow(this)">删除</a> </td> </tr> <tr > <td>祈求者</td> <td> <a href="#" onclick="deleteRow(this)">删除</a> </td> </tr> </table>
示例 2 :
练习-登陆时候,验证账号密码是否为空
<form method="post" action="/study/login.jsp" onsubmit="return login()"> 账号:<input id="name" type="text" name="name"> <br/> 密码:<input id="password" type="password" name="password" > <br/> <input type="submit" value="登陆"> </form> <script> function login(){ var name = document.getElementById("name"); if(name.value.length==0){ alert("用户名不能为空"); return false; } var password = document.getElementById("password"); if(password.value.length==0){ alert("密码不能为空"); return false; } return true; } </script>
示例 3 :
练习-提交数据,验证长度
<form method="post" action="/study/register.jsp" onsubmit="return register()"> 账号:<input id="name" type="text" name="name"> <br><br> <input type="submit" value="注册"> <br> </form> <script> function register(){ var name = document.getElementById("name"); if(name.value.length<3){ alert("用户名至少需要3位长度"); return false; } return true; } </script>
示例 4 :
练习-提交数据,验证年龄是否为数字
<form method="post" action="/study/register.jsp" onsubmit="return register()"> 账号:<input id="name" type="text" name="name"> <br><br> 年龄:<input id="age" type="text" name="age"> <br><br> <input type="submit" value="注册"> <br> </form> <script> function register(){ var name = document.getElementById("name"); if(name.value.length<3){ alert("用户名至少需要3位长度"); return false; } var age = document.getElementById("age"); if(age.value.length==0){ alert("年龄不能为空"); return false; } if(isNaN(age.value)){ alert("年龄必须是数字"); return false; } return true; } </script>