Javascript 试图使回车按钮';可点击';
我想让“搜索”按钮在单击“输入”时可单击 这是我的htmlJavascript 试图使回车按钮';可点击';,javascript,asp.net,javascript-events,Javascript,Asp.net,Javascript Events,我想让“搜索”按钮在单击“输入”时可单击 这是我的html <input type="text" runat="server" id="txtSearch" onkeypress="searchKeyPress(event);" <input type="button" runat="server" style="padding:5px;" id="butSearch" onserverclick="butSearch_Click" value="Search" disabled/
<input type="text" runat="server" id="txtSearch" onkeypress="searchKeyPress(event);"
<input type="button" runat="server" style="padding:5px;" id="butSearch" onserverclick="butSearch_Click" value="Search" disabled/>
然而,我得到了一个错误
'Uncuaght TypeError:Cannot call method click of nul'
关于我为什么会犯这样的错误,有没有更好的替代方法 那些runat=“server”
是必需的吗?您得到错误是因为当调用searchKeyPress
时,您的按钮还不存在。它要么是在加载DOMContentLoaded之前触发的,要么是asp.net正在用你的按钮做一些古怪的事情,使它完全脱离DOM
还有一些常规JavaScript提示:
function searchKeyPress(e) {
// a much cleaner "use var, or assign if not defined":
e = e || window.event;
// strict comparison:
if (e.keyCode === 13) {
// verify we have a button:
var btn = document.getElementById("butSearch");
if (btn) {
btn.click();
} else {
// btn does not exist. arbitrary code goes here
}
}
}
那些runat=“server”
是必需的吗?您得到错误是因为当调用searchKeyPress
时,您的按钮还不存在。它要么是在加载DOMContentLoaded之前触发的,要么是asp.net正在用你的按钮做一些古怪的事情,使它完全脱离DOM
还有一些常规JavaScript提示:
function searchKeyPress(e) {
// a much cleaner "use var, or assign if not defined":
e = e || window.event;
// strict comparison:
if (e.keyCode === 13) {
// verify we have a button:
var btn = document.getElementById("butSearch");
if (btn) {
btn.click();
} else {
// btn does not exist. arbitrary code goes here
}
}
}
在ASP.NET中,客户端生成的ID不是您在ASP.NET标记中看到的ID(请查看生成的源代码) 您需要调用控件的
ClientID
属性,以便通过javascript或jQuery访问它
你可以尝试:
function searchKeyPress(e) {
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13) {
document.getElementById('<%=butSearch.ClientID%>').click();
}
}
功能搜索按键(e){
如果(typeof e=='undefined'&&window.event){e=window.event;}
如果(e.keyCode==13){
document.getElementById(“”)。单击();
}
}
如果您了解ASP.NET ID是如何生成的,还可以使用控件的,将其设置为静态。在ASP.NET中,客户端生成的ID不是您在ASP.NET标记中看到的ID(请查看生成的源代码) 您需要调用控件的
ClientID
属性,以便通过javascript或jQuery访问它
你可以尝试:
function searchKeyPress(e) {
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13) {
document.getElementById('<%=butSearch.ClientID%>').click();
}
}
功能搜索按键(e){
如果(typeof e=='undefined'&&window.event){e=window.event;}
如果(e.keyCode==13){
document.getElementById(“”)。单击();
}
}
如果您了解ASP.NET ID是如何生成的,还可以使用控件的,将其设置为静态。您可以这样做:
function searchKeyPress(e) {
e = e || window.event;
var key = e.keyCode || e.which;
if (key == 13) {
document.getElementById("butSearch").click();
}
}
你可以这样做:
function searchKeyPress(e) {
e = e || window.event;
var key = e.keyCode || e.which;
if (key == 13) {
document.getElementById("butSearch").click();
}
}
尝试改为type=“submit”内部输入标记。尝试改为type=“submit”内部输入标记。使用.onclick()
而不是。单击()
。使用.onclick()
而不是。单击()。