添加母版页后,Javascript无法正常工作

时间:2017-02-17 06:45:51

标签: javascript asp.net master-pages

最初我能够在选择图像后预览图像。添加母版页后,javascript不再有效。

这是我的母版页

wkhtmltopdf 0.12.3 (with patched qt)

这是我的内容页

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>     
<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>

这是我的代码

<%@ Page Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Testing1.aspx.cs" Inherits="Testing.Testing1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript">
    function imagepreview(input)
    {
        if (input.files && input.files[0]) {
            var fildr = new FileReader();
            fildr.onload = function (e) {
                $('#Image1').attr('src', e.target.result);
            };
            fildr.readAsDataURL(input.files[0]);
        }
    }
</script>  
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">  

    <asp:FileUpload ID="FileUpload1" runat="server" />
    <br />
    <asp:Image ID="Image1" runat="server" height="100" Width="100" />
    <br />
    <br />
    <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    <br />
    <br />
    <asp:TextBox ID="tbRetrieve" runat="server"></asp:TextBox>
    <br />
    <asp:Button ID="btnRetrieve" runat="server" Text="Retrieve" OnClick="btnRetrieve_Click" />
    <br />
    <asp:Image ID="Image2" runat="server" />
    <br />
    <asp:Label ID="lblMessage" runat="server"></asp:Label>
    <br />
    <br />
    </asp:Content>

那么问题是什么?

2 个答案:

答案 0 :(得分:0)

在添加母版页时,查找控件ID的代码将被更改,您将不得不替换这样的代码。

<script type="text/javascript">
function imagepreview(input)
{
    if (input.files && input.files[0]) {
        var fildr = new FileReader();
        fildr.onload = function (e) {
            $('#<%=Image1.ClientID%>').attr('src', e.target.result);
        };
        fildr.readAsDataURL(input.files[0]);
    }
}

答案 1 :(得分:0)

你需要使用这样的代码才能在后面调用你的javascript方法。

<强> Page.ClientScript.RegisterStartupScript(this.GetType(), “CallMyFunction”, “MyFunction的()”,TRUE);