问题
I want to assign mouseclick
event to asp.net panel
:
protected void Page_Load(object sender, EventArgs e)
{
Panel p = new Panel();
p.Click += new EventHandler(b_Click);//but, this doesn't compiles correctly
}
protected void b_Click(object sender, EventArgs e)
{
//C#code
}
Is there any way to add click event to panel?
回答1:
Here is what you can do to make your panel clickable and handle the event at server side.
Place panel in your web form
<asp:Panel runat="server" ClientIDMode="Static" ID="clickMe">
Click here
</asp:Panel>
Add jQuery script library to your page.
<script src="http://code.jquery.com/jquery.min.js" language="javascript"
type="text/javascript"></script>
Define the following client side event handler
$(document).ready(function() {
$("#clickMe").click(function () {
__doPostBack('clickMe', '');
});
});
Handle the event at server side.
protected void Page_PreRender(object sender, EventArgs e)
{
this.Page.ClientScript.GetPostBackEventReference(clickMe, "");
}
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["__EVENTTARGET"] == "clickMe")
{
ClickMeOnClick();
}
}
The code in PreRender event handler is for asp.net framework to render __doPostBack function at cilent sides. If your page includes a control that causes an auto postback you don't need this code.
回答2:
Mouseclick event with jQuery 1.7:
$('#placeholderID').on('click', '#panelID', function(e){ });
回答3:
If you want a more easier solution, put a button before the panel closing tag, make, set the css style to cover the entire panel and opacity:0, adjust z-index to not cover your other elements, and just use your onclick method in code behind.
example:
css:
btn-panel{
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
opacity: 0;
z-index: -1;
}
asp:
<asp:Panel ID="myPanel" runat="server" >
//all your other elements here...
<asp:Button ID="Button1" runat="server" Text="" CssClass="btn-panel"
OnClick="YourButton_Click" />
</asp:Panel>
code behind:
protected void YourButton_Click(object sender, EventArgs e)
{
// Your Code Here...
}
There you go, no javascript nor jquery for doing the magic!!
来源:https://stackoverflow.com/questions/12739979/add-mouseclick-event-to-panel