如何在每个子页面上运行js?

时间:2011-11-16 03:45:20

标签: javascript asp.net

我正在尝试在每个子页面上运行我的javascript,masterpagecode:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WindowonUnload.Site1" %>

<!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>
    <asp:ContentPlaceHolder ID="head" runat="server">

    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
         <script>
             //window.addEventListener('unload', function () { alert('hahaha'); });
             window.onunload = function () {
                 alert('from webf master');
             }
    </script>
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

childpage:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="WindowonUnload.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

</asp:Content>

我做错了什么?

3 个答案:

答案 0 :(得分:0)

尝试将脚本标记放在母版页的内容占位符之外。

答案 1 :(得分:0)

试试这个:

    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WindowonUnload.Site1" %>

<!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>
    <head>
         <script>
             window.onunload = function () {
                 alert('from webf master');
             }
         </script>
    </head> 
    <asp:ContentPlaceHolder ID="head" runat="server">

    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

答案 2 :(得分:0)

将您的javascript代码放在MasterPage <Head>标记

<head runat="server">
    <title></title>
    <script type="text/jscript">
             window.onunload = function () {alert('from webf master');}
    </script>
</head>