2013-02-09 92 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。