练习一:修改程序清单9.1的代码,增加对phone字段是否为空的检测,让程序只输出一个条提示信息,说明哪个字段需要填写。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Page115 Practice: Canceling Default Behavior</title> <script> function checkform(){ document.getElementById("form1").onsubmit = function(){ var allowSubmit = true; var returnError = ""; if(document.getElementById("user").value ==""){ returnError += " 用户名不能为空 "; allowSubmit = false; } if(document.getElementById("phone").value ==""){ returnError += " 电话不能为空 "; allowSubmit = false; } if(allowSubmit){ returnError += " 数据内容填写正确,提交表单。 "; } alert(returnError); return allowSubmit; } } window.onload = checkform; </script> </head> <body> <form id="form1"> 用户名:<input type="text" value="" name="username" id="user" /> [必填项]<br/> 电话:<input type="text" value="" name="telephone" id="phone" /> [可选项]<br/> <input type="submit" value="提交" /> </form> </body> </html>
练习二:在由程序清单 9.3 和 9.4 组成的练习中,实现这样一个功能:双击 <div> 元素时清空其中的内容。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Adding and Removing Event Handlers</title> <script> function addEventHandler(element,eventType,handlerFunction){ if(element.addEventListener){ element.addEventListener(eventType,handlerFunction,false); } else if(element.attachEvent){ element.attachEvent('on'+eventType,handlerFunction); } } function removeEventHandler(element,eventType,handlerFunction){ if(element.removeEventListener){ element.removeEventListener(eventType,handlerFunction,false); } else if(element.detachEvent){ element.detachEvent('on'+eventType,handlerFunction); } } function appendText(e){ if(!e)var e = window.event; var element = (e.target) ? e.target : e.srcElement; document.getElementById('div1').innerHTML += element.id + "<br />"; } function removeOnclickA(){ removeEventHandler(document.getElementById("buttonA"),'click',appendText); } function removeOnclickB(){ removeEventHandler(document.getElementById("buttonB"),'click',appendText); } function reset(){ addEventHandler(document.getElementById("buttonA"),'click',appendText); addEventHandler(document.getElementById("buttonB"),'click',appendText); } window.onload = function(){ addEventHandler(document.getElementById("button-a"),'click',removeOnclickA); addEventHandler(document.getElementById("button-b"),'click',removeOnclickB); addEventHandler(document.getElementById("reset"),'click',reset); addEventHandler(document.getElementById("div1"),'dblclick',clear); reset();//初始化载入,调用方法并赋予每个按钮(区域)特定事件; clear();//清空DIV; } function clear(){ document.getElementById("div1").innerHTML = null; } </script> </head> <body> <input id="buttonA" type="button" value="A 按钮" /> <input id="button-a" type="button" value="移除 A 按钮点击事件" /> <br/> <input id="buttonB" type="button" value="B 按钮" /> <input id="button-b" type="button" value="移除 B 按钮点击事件" /> <br/> <input id="reset" type="button" value="重置初始状态" /> <div id="div1" style="border:1px solid black; width: 300px; height: 200px;"> </div> </body> </html>