javascript 为什么我会收到“无法读取空值的属性‘点击’错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27490678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do I get a "Cannot read property 'click' of null error
提问by SearchForKnowledge
Inside the BODY
tag:
里面的BODY
标签:
<asp:Panel ID="nmSearch" CssClass="searchBox" runat="server" DefaultButton="HiddenSearchNM">
<input type="text" runat="server" value="" placeholder="Search" id="searchB" class="styledTB searchB floatLeft" />
<a href="JavaScript:void(0);" onclick="SearchNMClick();" title="Search" class="styledBtnSearch searchAnchor floatLeft defaultLinks">
<asp:Image ImageUrl="~/images/searchWhite.png" CssClass="searchImg" runat="server" ToolTip="Search" AlternateText="Search" />
</a>
<asp:ImageButton ID="HiddenSearchNM" runat="server" CssClass="hideContent" ClientIDMode="Static" />
</asp:Panel>
Inside the HEAD
tag:
里面的HEAD
标签:
<script>
function SearchNMClick() {
document.getElementById('HiddenSearchNM').click();
}
</script>
I see the following error in the console:
我在控制台中看到以下错误:
Uncaught TypeError: Cannot read property 'click' of null
SearchNMClick
onclick
C# code behind which will fire off a search page from either Enter
or click:
后面的 C# 代码将从以下任一位置触发搜索页面Enter
或单击:
protected void HiddenSearchNM_Click(object sender, EventArgs e)
{
//MessageBox.Show("SEARCH NM");
strSMain = searchB.Value;
Response.Redirect("results.aspx?searchtext=" + strSMain +"&folderid=0&searchfor=all&orderby=title&orderdirection=ascending");
}
But when I hit enter while in the textbox or the button click, I get the error above.
但是当我在文本框中或单击按钮时按 Enter 键时,出现上述错误。
How do I resolve the error.
我该如何解决错误。
So weird, when I check the HTML source I see this (not sure why the ID is being changed):
太奇怪了,当我检查 HTML 源代码时,我看到了这个(不知道为什么要更改 ID):
<input type="image" name="ctl00$CUSTOM_Area_Top$HiddenSearchNM" id="ctl00_CUSTOM_Area_Top_HiddenSearchNM" class="hideContent" ClientIDMode="Static" src="" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$CUSTOM_Area_Top$HiddenSearchNM", "", true, "", "", false, false))" style="border-width:0px;" />
采纳答案by dario
You may change you JS function to:
您可以将 JS 函数更改为:
function SearchNMClick() {
document.getElementById('<%# HiddenSearchNM.ClientID %>').click();
}
回答by beautifulcoder
Use a Page
directive to set static ids
使用Page
指令设置静态 ID
<%@ Page ClientIDMode="static" %>
That should work with your id selector.
这应该适用于您的 id 选择器。
Also, check your rendered HTML for your ImageButton
. If everything is setup correctly, it should preserve the ID
.
此外,请检查您呈现的 HTML 以获取ImageButton
. 如果一切设置正确,它应该保留ID
.