首页javascriptkeyJavascript Event - 如何向新创建的元素添加事件处理程序...

Javascript Event - 如何向新创建的元素添加事件处理程序...

我们想知道如何向新创建的元素添加事件处理程序。...

 
<HTML>
<BODY>
<SCRIPT>
function handler(e){
   if (navigator.appName == "Microsoft Internet Explorer"){
      e = window.event;
      console.log("Event Type: " + e.type);
      if (e.keyCode) 
         console.log("Keycode: " + String.fromCharCode(e.keyCode));
      if (e.altKey) 
         console.log("Alt Key: " + e.altKey);
      if (e.ctrlKey) 
         console.log("Ctrl Key: " + e.ctrlKey);
      if (e.shiftKey) 
         console.log("Shift Key: " + e.shiftKey);
   } else {
      console.log("Event Type: " + e.type);
      if (e.target) 
         console.log("Target: " + Object.prototype.toString.apply(e.target));
      if (e.target.name) 
         console.log("Target Name: " +  e.target.name);
      if (e.which) 
         console.log("Which: " +  String.fromCharCode(e.which));
      if (e.modifiers) 
         console.log("Modifiers: " +  e.modifiers);
   }
}


function startForm(){
   //document.theForm.userLname.onblur = handler;
   document.theForm.userLname.onchange = handler;
   //document.theForm.userLname.onfocus = handler;
   document.theForm.userLname.onkeydown = handler;
   document.theForm.userLname.onkeypress = handler;
   document.theForm.userLname.onkeyup = handler;

}
   
</SCRIPT>
<FORM name="theForm">
    Enter Your First Name:
    <INPUT type=text name="userLname">
    <INPUT type=button name="theButton" value="START" onClick="startForm();">
</FORM>
</BODY>
</HTML>