ASP.NET 用户控件中的 Javascript 函数 [英] Javascript functions inside ASP.NET User Control

查看:21
本文介绍了ASP.NET 用户控件中的 Javascript 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 生成两个同名函数的代码,有什么问题:

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()" />

并且任何按钮上的鼠标悬停事件都会调用第二个函数.我可以通过将带有客户端 ID 的 Java 脚本代码直接添加到 onmouseover 属性来解决此问题.

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.

附言Javascript 代码会多很多,我只是在上面加了两个字符串.

P.S. There will be much more Javascript code, I added two string upper just for example.

推荐答案

您需要使用 ClientScriptManager - 这样它们就可以注册一次,无论控件添加到页面的频率如何:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆