If you want to add a click event handler to all DIVs using jQuery, you can do so with the following code:
HTML:
<div style="background-color: red; width: 50px; text-align: center;" id="one">
<a>Hello</a>
</div>
<br/>
<div style="background-color: yellow; width: 50px; text-align: center;" id="two">
<a>World</a>
</div>
JavaScript:
$("div").click(function (event) {
alert(event.currentTarget.id);
});
You can view a working example on jsFiddle.
To handle server-side logic, you can use the __doPostBack()
function in your jQuery click event handler like this:
$("div").click(function (event) {
__doPostBack(event.currentTarget.id,'');
});
On the server-side, you can retrieve the ID of the clicked element using the __EVENTTARGET
value in the Request
object:
if (IsPostBack)
{
string ControlID = string.Empty;
if (!String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
{
ControlID = Page.Request.Params["__EVENTTARGET"];
Control postbackControl = Page.FindControl(ControlID);
// Perform actions based on the control that caused the post back
}
}