ASP.NET用户控件中的JavaScript功能 [英] Javascript functions inside ASP.NET User Control
问题描述
我创建ASP.NET用户控件与javascript函数:
I created ASP.NET user control with javascript function :
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="BingTranslator.Web.WebUserControl1" %>
<script type="text/javascript">
function example() {
alert('<%=ExampleButton.ClientID%>');
return false;
}
</script>
<asp:Button ID="ExampleButton" runat="server" Text="Example"/>
我要叫榜样功能时,用户移动鼠标按键,所以我加了按钮的属性:
I want to call "example" function when user move mouse to button, so I added attribute for button:
ExampleButton.Attributes.Add("onmouseover", "example()");
它工作得很好,但是当我需要同一页上的两个控件我有一个问题。 ASP.NET生成code与两个名称相同的功能,什么是错的:
It works well, but when I need two controls on same page I got a problems. ASP.NET generates code with two functions with same name, what is wrong:
<script type="text/javascript">
function example() {
alert('TestControl1_ExampleButton');
return false;
}
</script>
<input type="submit" name="TestControl1$ExampleButton" value="Example" id="TestControl1_ExampleButton" onmouseover="example()" />
<script type="text/javascript">
function example() {
alert('TestControl2_ExampleButton');
return false;
}
</script>
<input type="submit" name="TestControl2$ExampleButton" value="Example" id="TestControl2_ExampleButton" onmouseover="example()" />
和永远的onmouseover上的任何按钮事件将调用第二功能。我加入的Java脚本code。与客户端1d直接的onmouseover attriburte我能解决这个问题。
And always onmouseover event on any button will call second function. I am able resolve this issue by adding java script code with client Id directly to attriburte onmouseover.
ExampleButton.Attributes.Add("onmouseover", "[Here will be javascript code]");
但它不是很和谐的解决方案,对我来说。请指教,我如何才能更好地解决这些问题。
But it is not very harmonious solution as for me. Please advise, how I can better resolve such issue.
P.S。将有更多的Javascript code,我添加了两个字符串只是举例上。
P.S. There will be much more Javascript code, I added two string upper just for example.
推荐答案
您需要注册脚本<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.aspx\"><$c$c>ClientScriptManager$c$c> - 这样可以将它们注册一次,而不管频率的控制已被添加到页:
You need to register your scripts with ClientScriptManager
- this way they can be registered once, regardless of how often the control has been added to the page:
// 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);
}
这篇关于ASP.NET用户控件中的JavaScript功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!