为什么我的JavaScript不能与我的UserControl交互?

时间:2011-01-18 08:49:57

标签: javascript asp.net user-controls getelementbyid

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>

<script type="text/javascript">
    function Incrementer() {
        var txtBox = document.getElementById('MainContent_TextBox1').value;

        var i = parseInt(txtBox);
        i = i + 1;
        var v = i + "";
        document.getElementById('MainContent_TextBox1').value = v;
        return false;
    }
    function Decrementer() {
        var txtBox = document.getElementById('MainContent_TextBox1').value;

        var i = parseInt(txtBox);
        i = i - 1;
        var v = i + "";
        document.getElementById('MainContent_TextBox1').value = v;
        return false;
    }

</script>
<asp:TextBox ID="TextBox1" runat="server" Text="0"></asp:TextBox><br />
<asp:Button ID="Button1"  runat="server" Text="Up"  OnClientClick="return Incrementer();"/>
<asp:Button ID="Button2" Text="Down" runat="server" OnClientClick="return Decrementer();"/>

Default.aspx如下: -

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>
    <%@ Register Src="~/WebUserControl.ascx" TagName="IncrementerUserControl" TagPrefix="uc1" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<uc1:IncrementerUserControl ID="Incrementer1" runat="server"/>
    </asp:Content>

当我将其添加到usercontrol中时,增量器功能现在不起作用。为什么?如果我在没有用户控制的情况下使用增量器和减量器,它可以正常工作。

1 个答案:

答案 0 :(得分:5)

MainContent_TextBox1是问题所在。当您在用户控件中包含TextBox时,由于runat=server

,其名称会被破坏

尝试使用: document.getElementById('%=TextBox1.ClientID %')

请参阅:

http://jagregory.com/writings/how-to-use-clientids-in-javascript-without-the-ugliness/