【问题标题】:Javascript functions inside ASP.NET User ControlASP.NET 用户控件中的 Javascript 函数
【发布时间】:2011-05-23 22:26:43
【问题描述】:

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

<%@ 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"/>

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

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

效果很好,但是当我需要在同一页面上使用两个控件时,我遇到了问题。 ASP.NET 生成具有两个同名函数的代码,有什么问题:

<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 事件都会调用第二个函数。我可以通过将带有客户端 ID 的 java 脚本代码直接添加到 onmouseover 属性来解决此问题。

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

但这对我来说不是很和谐的解决方案。请告知,我如何才能更好地解决此类问题。

附:会有更多的Javascript代码,我在上面添加了两个字符串。

【问题讨论】:

    标签: c# javascript asp.net user-controls webforms


    【解决方案1】:

    您需要使用this.id

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

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

    【讨论】:

    • 但这无论如何都会创建许多相同的 Javascript 函数,这是应该避免的。另外,我猜你想在ready 事件中写load_v&lt;%= this.ID %&gt;(),对吧?那fromclick 是干什么用的?
    【解决方案2】:

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

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

    【讨论】:

    • 为什么这不是公认的解决方案?你是生命的救星:D
    【解决方案3】:

    您需要使用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);
    }
    

    【讨论】:

    • 是的,这是一种可能的方式,但我不想将 javascript 代码移动到 CS 文件中,因为它太大了。
    • @Anton - 听起来你需要重构你的 CS 文件。
    猜你喜欢
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多