我想让“搜索”按钮在点击回车后可点击。
这是我的 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/>
这是我正在使用的 JavaScript:
function searchKeyPress(e) {
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13) {
document.getElementById("butSearch").click();
}
}
但是我收到错误
'Uncaught 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
}
}
}
关于javascript - 尝试制作输入按钮 'clickable',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17089289/