By Daniel Du
Let’s say we are trying to add OnClick event handler for a group of button, a straight-forward way is to add “onclick” for each element of the group, like this:
<input id="Button1" type="button" value="button1" onclick="handler1()" /><br /> <input id="Button2" type="button" value="button2" onclick="handler2()" /><br />
But it will be pretty troublesome and tedious if you have many elements in this group. A better way is to add a parent element for this group and add event handler for this parent element, the click event will be bubbled up the parent element and the source element of event can be identified by id. For IE or Chrome, it is event.srcElement.id, for Firefox, it is event.target.id. Code goes as below:
<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("you clicked button"+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);
});
}
</script>
<h2>
Welcome to ASP.NET!
</h2>
<div id="btnGroup">
<input id="Button1" type="button" value="button1" /><br />
<input id="Button2" type="button" value="button2" /><br />
<input id="Button3" type="button" value="button3" /><br />
<input id="Button4" type="button" value="button4" /><br />
<input id="Button5" type="button" value="button5" /><br />
<input id="Button6" type="button" value="button6" /><br />
<input id="Button7" type="button" value="button7" /><br />
<input id="Button8" type="button" value="button8" /></div>
Comments
You can follow this conversation by subscribing to the comment feed for this post.