If multiple buttons on a page need to be added for event processing, the processing methods for these elements are similar. For example, there are 10 buttons, we can write an event processing function for each button, which is time-consuming and laborious.
For example:
<input id="Button1" type="button" value="button1" onclick="handler1()" /><br /><input id="Button2" type="button" value="button2" onclick="handler2()" /><br />
A better way is to process events between their parent objects. JavaScript events are transmitted to their parent objects through the bubbling mechanism, and the starting element of the event can be obtained through srcElement. You can add a div element on the button and add onclick event processing to the div. This makes the code concise and execution more efficient.
<script type="text/javascript"> window.onload = function () { var isFirxFox = function () { return navigator.userAgent.indexOf("Firefox") > 0 ? true : false; } var clickHandler = function (index) { //handle click event here alert(index); } var btnGroup = document.getElementById("btnGroup"); btnGroup.addEventListener("click", function (event) { var targetId; if (isFirxFox()) { //for Firefox targetId = event.target.id; } else { //For IE, Chrome targetId = event.srcElement.id; } var index = targetId.slice(6); clickHandler(index);// switch (targetId) {// case "Button1": alert("btn1 clicked"); break;// case "Button2": alert("btn2 clicked"); break;// case "Button3": alert("btn3 clicked"); break;// case "Button4": alert("btn4 clicked"); break;// case "Button5": alert("btn5 clicked"); break;// default:// alert("other btns are clicked");// } }); }</script>