动态将onserverclick事件添加到HtmlAnchor [英] Adding onserverclick event to a HtmlAnchor dynamically
问题描述
我有一个页面,想将onserverclick事件附加到我现有的页面上 HtmlAnchor.
I've got a page and would like to append the onserverclick event to my existing HtmlAnchor.
在设计视图中,我首先添加控件
In the design view I am first adding the control
<a runat="server" id="lnkFre" title="FR" onclick="document.getElementById('ctl00_hidLang').value='en-US';"><span>Français</span> </a>
我尝试过这样.
HtmlAnchor lnkFre = FindControl("lnkFre") as HtmlAnchor;
lnkFre.ServerClick += new EventHandler(lnkLang_Click);
此处lnkLang_Click是可从此页面访问的类中的事件.
Here the lnkLang_Click is an event in a class which is accessible from this page.
但是在运行时没有添加它.
But at runtime it is not being added.
我希望有这样的东西.
<a runat="server" id="lnkFre" title="FR" onserverclick="lnkLang_Click" onclick="document.getElementById('ctl00_hidLang').value='fr-BE';"><span>Français</span> </a>
这样有可能吗?还是请我推荐另一种方法.
Is this possible in this way? Or kindly suggest me another method.
非常感谢
推荐答案
这对我有用:
HTML
<a href="#A" runat="server" id="MyAnchor" onclick="alert('test');return true;">A</a>
隐藏代码
protected void Page_Load(object sender, EventArgs e)
{
HtmlAnchor lnkFre = MyAnchor as HtmlAnchor;
lnkFre.ServerClick += new EventHandler(lnkFre_ServerClick);
}
void lnkFre_ServerClick(object sender, EventArgs e)
{
throw new NotImplementedException();
}
由于事件是动态绑定的,因此您显然无法在运行时看到标记,但它将调用服务器click事件.
You obviously won't be able to see the markup at runtime as the event is being bound dynamically but it will call the server click event.
也请注意onclick事件结束时的return(true);
.服务器单击也必须触发.
Please also note the return(true);
at the end of the onclick event. This is necessary for the server click to also fire.
这篇关于动态将onserverclick事件添加到HtmlAnchor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!