繁体   English   中英

ASPX中的简单jQuery Hello World

[英]Simple jQuery Hello World in ASPX

我真的不明白为什么这个简单的例子不起作用:SI有一个WebApplication,其中有一个脚本:

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);
    }

我看不出这是怎么回事。 我试图将scrit直接包含在aspx内,但什么也没有。 然后,我尝试进入一个简单的html页面,效果很好。

我想在页面中使用使用jQuery的绘图库,所以如果这样一个简单的示例给我带来很多问题,我将远不能取得成功...大声笑

尝试在所使用的任何浏览器中检查调试控制台,以查看“ $”是否未定义。 听起来好像您在使用完整的ASP.NET方法时缺少jquery。

由于使用了母版页,因此该按钮的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!");
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM