主页引用javascript在visual studio中不起作用

时间:2016-07-22 06:39:40

标签: javascript

我在MasterPage.master中有这段代码

<head runat="server">
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="<%# ResolveUrl("~/") %>script.js" ></script>

<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>

<body>
  <div class="handle">Click me</div>

</body>

我在script.js文件中有这段代码

$('.handle').on('click', function () {
   alert('hello world');
});

当我点击div部分时,我没有像我应该拥有的警报信息。
我在Default.aspx中有这段代码

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
 </asp:Content>

 <asp:Content ID="Content2" ContentPlaceHolderID="mainContent" Runat="Server">
 </asp:Content>

这是我在visual studio中的项目目录

enter image description here

2 个答案:

答案 0 :(得分:1)

在创建DOM之前执行JavaScript。将script.js代码更改为

$(document).ready(function () {
  $('.handle').on('click', function () {
    alert('hello world');
  });
});

jQuery live/on仅在加载DOM完成后才有效。作为替代方案,在div声明之后放置您的JavaScript代码。

答案 1 :(得分:0)

我已经尝试过你的代码,对我来说似乎没问题。让我与您分享该代码。

MasterPage.master:

            <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

            <html xmlns="http://www.w3.org/1999/xhtml">
            <head runat="server">
                <title></title>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
                <asp:ContentPlaceHolder id="head" runat="server">
                </asp:ContentPlaceHolder>
            </head>
            <body>
                <form id="form1" runat="server">
                <div>
                    <div class="handle">Click me</div>
                    <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

                    </asp:ContentPlaceHolder>
                </div>
                </form>
            </body>
            </html>
            <script type="text/javascript">
                $('.handle').on('click', function () {
                    alert('hello world');
                });
            </script>

Default.aspx的:

            <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

            <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
            </asp:Content>
            <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
            </asp:Content>