ASP.NET用户控件中的Javascript函数

我用javascript函数创建了ASP.NET用户控件:

  function example() { alert(''); return false; }   

当用户将鼠标移动到按钮时,我想调用“example”函数,所以我为按钮添加了属性:

 ExampleButton.Attributes.Add("onmouseover", "example()"); 

它运作良好,但当我在同一页面上需要两个控件时,我遇到了问题。 ASP.NET生成具有两个具有相同名称的函数的代码,这是错误的:

  function example() { alert('TestControl1_ExampleButton'); return false; }    function example() { alert('TestControl2_ExampleButton'); return false; }   

并且任何按钮上的onmouseover事件总是会调用第二个函数。 我可以通过将带有客户端ID的java脚本代码直接添加到attriburte onmouseover来解决此问题。

 ExampleButton.Attributes.Add("onmouseover", "[Here will be javascript code]"); 

但对我来说这不是一个非常和谐的解决方案。 请指教,我如何才能更好地解决此类问题。

PS将会有更多的Javascript代码,例如我添加了两个字符串upper。

您需要使用ClientScriptManager注册脚本 – 这样,无论控件添加到页面的频率如何,都可以注册一次:

 // Get a ClientScriptManager reference from the Page class. ClientScriptManager cs = Page.ClientScript; // Check to see if the startup script is already registered. if (!cs.IsStartupScriptRegistered(cstype, csname1)) { String cstext1 = "alert('Hello World');"; cs.RegisterStartupScript(cstype, csname1, cstext1, true); } 

我在另一个站点找到了一个允许您使用外部文件的解决方案

 if (!Page.ClientScript.IsClientScriptIncludeRegistered("key")) { string url = ResolveClientUrl("~/Scripts/file.js"); Page.ClientScript.RegisterClientScriptInclude("key", url); } 

你需要使用this.id

 $(document).ready(function () { load_v<%= this.ID %> }); function load_v<%= this.ID %>(fromclick) { alert('anything'); } 

因此,即使您在同一页面中需要两个或更多相同的控件,它们也会有不同的ID。 希望这可以帮助! 欢呼:)