簡體   English   中英

ASP.NET 用戶控件中的 Javascript 函數

[英]Javascript functions inside ASP.NET User Control

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

並且任何按鈕上的鼠標懸停事件都會調用第二個函數。 我可以通過將帶有客戶端 ID 的 Java 腳本代碼直接添加到 onmouseover 屬性來解決此問題。

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

但對我來說這不是很和諧的解決方案。 請指教,我如何才能更好地解決此類問題。

PS會有更多的Javascript代碼,我只是例如添加了兩個字符串。

我在另一個站點找到了一個解決方案,它允許您使用外部文件

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。 希望這可以幫助! 歡呼:)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM