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

15

我创建了一个具有 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"/>

我希望在用户将鼠标移动到按钮上时调用“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事件都会始终调用第二个函数。我能通过直接向onmouseover属性添加客户端ID的JavaScript代码来解决此问题。

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

但是对我来说,这不是一个很和谐的解决方案。请建议一下,我如何更好地解决这个问题。

附言:将会有更多的JavaScript代码,我只是为了举例添加了两个字符串。

3个回答

38

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

if (!Page.ClientScript.IsClientScriptIncludeRegistered("key"))

{

   string url = ResolveClientUrl("~/Scripts/file.js");

   Page.ClientScript.RegisterClientScriptInclude("key", url);

}

4
为什么这个答案没有被接受呢?你是我的救星 :D - tfrascaroli

9

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

1
是的,这是一种可能的方法,但由于它的巨大体积,我不想将JavaScript代码移动到CS文件中。 - Anton
3
听起来你需要重构你的CS文件。 - Oded

9
您需要使用 this.id
$(document).ready(function () {
    load_v<%= this.ID %>    
});

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

所以,即使您需要在同一页中使用两个或更多相同的控件,它们也会有不同的ID。希望这可以帮到您!祝好 :)

但是这将创建许多相同的Javascript函数,这是应该避免的。另外,我猜在“ready”事件中,你想要写“load_v<%= this.ID %>()”,对吗?那个“fromclick”是什么意思? - Andrew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接