且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不单击锚标签的情况下触发Onclick事件

更新时间:2022-11-03 09:55:30


<a href="default.aspx" runat="server" id="anchor1"> Click here </a>





protected void Page_Load(object sender, EventArgs e)
{
    anchor1.ServerClick +=new EventHandler(anchor1_Click);
}
protected void anchor1_Click(object sender, EventArgs e)
{
    Response.Write("<script>alert('hello')</script>");
}


***的问候
M.mitwalli


Best Regards
M.mitwalli


这绝对是不可能的,但实际上您不需要它.您只能在声明了该事件的类或结构中触发某些事件,甚至不能在派生类中触发.与常规"委托实例相反,这是事件的重要防呆功能之一.有关更多信息,请参见我过去的回答:
由于我们有多播委托,所以为什么我们需要事件吗? [ ^ ].

在现实生活中,没有任何情况需要从声明类型外部触发事件,因此这就是.NET事件以其设计方式进行设计的原因.实际上,您只需要调用某些与Click事件的事件处理程序完全相同的方法即可.这是非常通用的方法:创建一个带有所需参数的单独方法,并在代码中的两个或多个不同位置调用它:一个来自事件处理程序(这是事件处理程序应执行的所有代码),而在其他地方,您想模拟点击".那是.很简单,不是吗?



由于错误,尽管我是Swetha Garlapati(见下文)的评论来自OP,所以我尝试以这种错误的假设进行回答.因此,下一段是从头开始".但是,下面的文本部分说明了JavaScipt中出现此问题的方式..[END EDIT2]

您应该已经说明您在谈论HTML和JavaScript.您的问题被标记为"C#".

好的,JavaScript的局限性要少得多,但是思想是相同的:
This is absolutely impossible, but you actually don''t need it. You can fire some events only in the class or structure where this event is declared, not even in derived class. This is one of important fool-proof features of events as opposed to "regular" delegate instances. For more information, please see my past answer:
Since we have multicast delegates, why do we need events?[^].

In real life, there are no situations where you need to fire an event from outside the declaring type, and this is why .NET events are designed the way they are designed. In fact, you merely need to call some method which would do exactly the same as some event handler of your Click event. Here is the very general recipe: create a separate method with required parameters and call it from two or more different places in you code: one from the event handler (and this is all the code of your event handler should do) and elsewhere, where you wanted to "simulate the click". That''s is. Simple, isn''t it?



By mistake, I though that the comment by Swetha Garlapati (see below) was from OP, so I tried to reply in this wrong assumption. Therefore, the next paragraph is "scratched out". However, the portion of the text below illustrates how this problems looks in JavaScipt..[END EDIT2]

You should have explained that you are talking about HTML and JavaScript. You question is tagged as "C#".

OK, JavaScript has much less limitations, but the idea is the same:
<html>
    <head>
        <title>...</title>
        <script type="text/javascript"><!--
            function clickHandler() {
                window.location.href="http://www.codeproject.com";
            }
            //and call this function elsewhere; it will "simulate" your click
        --></script>
    </head>
<body>

<input type=button onclick="clickHandler()" value="Click here">

</body>
</html>



—SA



—SA