Is there a way to add an onclick event to an ASP.N

2019-01-23 12:14发布

I wanted to do something like this:

<asp:Label ID="lblMyLabel" onclick="lblMyLabel_Click" runat="server">My Label</asp:Label>

I know that in Javascript I can do:

<span onclick="foo();">My Label</span>

So I'm wondering why I can't do that with a Label object.

10条回答
手持菜刀,她持情操
2楼-- · 2019-01-23 12:29

you could always roll out your own control which produces a span, with the .net's standard postback javascript, but as stated earlier using a linklabel with a CSS class would be easier

查看更多
Bombasti
3楼-- · 2019-01-23 12:30

I think you can, but it's a client-side onclick handler, not server side. It will complain about the attribute not being supported (or some such) but I think it renders correctly. If you want to to a server-side handler, I think you'll need to do a LinkButton.

查看更多
Lonely孤独者°
4楼-- · 2019-01-23 12:31

As far as I know that's impossible. Label control emits <span> element which is “unclickable” on the server side. You would need to replace your Label control with a LinkButton.

查看更多
Anthone
5楼-- · 2019-01-23 12:31

You need to create a class object that inherits from the label and onclick event handler which will be a method by yourslef and use your object as a custom label.

查看更多
走好不送
6楼-- · 2019-01-23 12:32

If you want an onclick event, why don't you use a linkbutton, which has the onclientclick event:

<asp:linkbutton id="lblMyLink" onclientclick="lblMyLink_Click" runat="server">My Label</asp:linkbutton>

You can use CSS to make the link look like whatever you want

查看更多
太酷不给撩
7楼-- · 2019-01-23 12:34

Another hack would be to use a hidden link or button with style="display:none;" and trigger the click on the server control from a javascript function in the span.

Something like this:

<asp:linkbutton id="lblMyLink" onClick="lblMyLink_Click" runat="server" style="display:none;">My Link</asp:linkbutton>
<span onclick="document.getElementById('lblMyLink').click();">My Label</span>
查看更多
登录 后发表回答