2013-02-09 91 views
0

我真的不明白,爲什麼這個簡單的例子不工作:S 我有web應用中,我有一個劇本:簡單的jQuery的Hello World在ASPX

function myAlert() {  
    $("#Button1").click(function() { 
     alert("Hello world!"); 
    }); 
} 

在我的ASP頁面,我有這個簡單的代碼

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Graph.aspx.cs" Inherits="WebApplication.Graph" %> 
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"> 
</asp:Content> 
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
<asp:Button ID="Button1" runat="server" Text="Button" Width="100px"/> 
</asp:Content> 

最後我註冊CS中的腳本:

protected override void OnPreLoad(EventArgs e) 
    { 
     Page.ClientScript.RegisterClientScriptInclude("jQuery", 
         ResolveUrl(@"Scripts\jquery-1.4.1.js")); 
     Page.ClientScript.RegisterClientScriptInclude("jMyAlert", 
      ResolveUrl(@"Scripts\MyAlert.js")); 
     // check if the start up script is already registered with a key 
     if(!Master.Page.ClientScript.IsStartupScriptRegistered("jMyAlert")) 
     { 
      // since it is not registered, register the script 
      Master.Page.ClientScript.RegisterStartupScript 
       (this.GetType(), "jMyAlert", "myAlert();", true); 
     } 
    } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     ScriptManager.RegisterStartupScript(this, this.GetType(), "jMyAlert", "myAlert()", true); 
    } 

我不看看這有什麼問題。我試圖直接在aspx中包含scrit,但沒有。然後我嘗試一個簡單的HTML頁面,它工作正常。

我想用使用jQuery一個繪圖庫在我的網頁,所以我很遠的成功,如果這樣一個簡單的例子使我這麼多的問題...笑

回答

0

由於使用母版頁,該按鈕的ID不會是#Button1。嘗試查看源代碼來查看我的意思。

要解決這個問題,您需要能夠在JavaScript中看到實際的ID。

像這樣的事情在你的Page_Load方法:

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), 
    "Button1Id", string.Format("var Button1Id = '{0}';", Button1.ClientID), true); 

會在您的網頁以下內容:

<script type="text/javascript"> 
//<![CDATA[ 
var Button1Id = 'Button1';//]]> 
</script> 

然後意味着你myAlert方法將需要看起來像這樣:

function myAlert() { 
    $("#" + Button1Id).click(function() { 
     alert("Hello world!"); 
    }); 
} 
+0

非常感謝!我注意到它在源代碼中,但我認爲這只是一個'通用'的名稱給按鈕,就像使用反編譯器時一樣... – GuillaumeA 2013-02-09 03:54:46

1

嘗試檢查中調試控制檯無論您使用的瀏覽器是否未定義「$」。這聽起來像是在使用完整的ASP.NET方法時缺少jquery。