This article describes the method of JS scripts to dynamically add events to tag controls. Share it for your reference, as follows:
<!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"><script language="javascript">function set(){var obj = document.getElementById("fy");//obj.attachEvent('onfocus', add); //Add //obj.setAttribute('onfocus',add); //It will replace the original event method //obj.onfocus=add;//equivalent obj.setAttribute('onfocus',add); if(window.addEventListener){//Event codes of other browsers: Mozilla, Netscape, Firefox//The order of added events is the execution order//Note that the event with on is added with addEventListener, without adding onobj.addEventListener('focus', add, false);}else{//IE event code adds add on the original event Method obj.attachEvent('onfocus',add);}}function add(){alert("Event added successfully");}</script><body><input type="text" onfocus="alert('Preset Event');" id="fy" /><input type="button" onclick="set();" value="sssss"/></body></html>PS: The code layout seems to be not satisfactory. Here I recommend several code formatting tools to you. I believe that it can be used in future programming development:
C language style/HTML/CSS/json code formatting and beautification tools:
http://tools.VeVB.COM/code/ccode_html_css_json
Online JavaScript code beautification and formatting tools:
http://tools.VeVB.COM/code/js
JavaScript code beautification/compression/formatting/encryption tools:
http://tools.VeVB.COM/code/jscompress
Online JSON code verification, inspection, beautification and formatting tools:
http://tools.VeVB.COM/code/json
json code online formatting/beautification/compression/editing/converting tools:
http://tools.VeVB.COM/code/jsoncodeformat
For more information about JavaScript, please check this site's special topics: "Summary of Ajax Operation Skills in JavaScript", "Summary of JSON Operation Skills in JavaScript", "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm techniques", "Summary of JavaScript animation effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm techniques", "Summary of JavaScript traversal algorithms and techniques", and "Summary of JavaScript mathematical operations usage"
I hope this article will be helpful to everyone's JavaScript programming.