【发布时间】:2012-10-05 10:22:04
【问题描述】:
我想在按下 Enter 按钮时运行一个 js 函数。 在 IE、Chrome 和 Opera 中一切正常,但在 Safari 中出现错误(解释如下)。
我需要一个纯 Javascript 解决方案,不是 jQuery。
这是函数:
function pressSearch(e) {
if (typeof e == 'undefined' && window.event) {
e = window.event;
}
var charCode = (e.which) ? e.which :
((e.charCode) ? e.charCode :
((e.keyCode) ? e.keyCode : 0));
if (charCode == 13) {
document.getElementById('enterSearch').click();
}
}
这是HTML:
<input type="text" id="searchKey" onkeypress="pressSearch(event)">
<div id="enterSearch">Search</div> // This is the "button"
我收到此错误:
// Safari
TypeError: 'undefined' is not a function
(evaluating 'getElementById('enterSearch').click()')
我做错了什么?
编辑:我已经修复了 Mozilla Firefox 错误。
【问题讨论】:
-
我将您的代码复制并粘贴到 Firefox 中,但没有出现错误...您能提供live demo吗?
-
我投了赞成票只是因为“我不想要 jQuery”这一行。
标签: javascript