ASP.NET Control的JavaScript getElementById返回null?

12 javascript asp.net getelementbyid

我使用JavaScript,在执行期间出现此错误:

Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object
Run Code Online (Sandbox Code Playgroud)

我的代码:

<asp:Content ID="content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script language="javascript" type="text/javascript">
    function ConfirmTransfere() {
        if (confirm("Syatem not allow negative inventory, would you like to continue ?") == true) {
            document.getElementById("btnAlelrt").click();

        }       
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="uxContainer" runat="server">
    <ContentTemplate>
 <table> 
<tr>
        <td>
        <asp:Button ID="uxTransfer" runat="server" Text="Transfer" OnClick="uxTransfer_Click" /> 
        <asp:Button ID="btnAlelrt" runat="server" Text="GetDetails" OnClick="btnAlelrt_Click" />       
        </td>
        </tr>
</table>
    </ContentTemplate>
<Triggers>
    <asp:PostBackTrigger ControlID="uxTransfer" />    
    </Triggers>
    </asp:UpdatePanel>

 </asp:Content>
Run Code Online (Sandbox Code Playgroud)

kem*_*002 25

这个:

function ConfirmTransfere() {
        if (confirm("Syatem not allow negative inventory, would you like to continue ?") == true) {
            document.getElementById("btnAlelrt").click();

        }       
Run Code Online (Sandbox Code Playgroud)

需要是这样的:

function ConfirmTransfere() {
        if (confirm("Syatem not allow negative inventory, would you like to continue ?") == true) {
            document.getElementById('<%=btnAlert.ClientID%>').click();

        }     
Run Code Online (Sandbox Code Playgroud)

问题是您的按钮是一个ASP.Net控件,并将生成它自己的客户端ID,这将与您指定的ID不同.输入代码<%=btnAlert.ClientID%>将生成的一个发布到浏览器.

  • 上帝,我讨厌asp.net (3认同)

alg*_*eat 6

你可以用这个:

document.getElementById('<%= btnAlelrt.ClientID %>').click()
Run Code Online (Sandbox Code Playgroud)

从ASP.NET 4.0开始,您可以为您的元素使用ClientIDMode属性.如果将其设置为,Static则该ClientID值将设置为ID属性的值:

<asp:Label ID="Label1" runat="server" ClientIDMode="Static" />
Run Code Online (Sandbox Code Playgroud)

将呈现如下:

<span id="Label1" name="ctl00$MasterPageBody$ctl00$Label1" />
Run Code Online (Sandbox Code Playgroud)