我有以下示例,可以轻松检测到“Enter”键按下并正确处理它。这里是:
<!DOCTYPE html>
<html>
<head>
<title>keyCode example</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#search-input").keyup(function (event) {
event = event || window.event;
if (event.keyCode == 13 || event.which == 13) {
$("#search-button").click();
}
});
$("#search-button").click(function () {
var theUrl = "http://www.yahoo.com/"
window.location = theUrl;
});
});
</script>
</head>
<body>
<input id="search-input" name="search" type="text"/>
<button id="search-button" type="button" alt="Search">Search</button>
</body>
</html>
这对我来说在所有流行的浏览器中都有效。
问题是这段代码在我的生产环境中除了 Firefox 之外的任何浏览器中都不起作用。
在我的生产环境中,该脚本也内置于$(document).ready
函数并位于单独的“main.js”文件中。调试模式显示,当我在文本字段中输入字母或数字时,脚本运行正确。当我按“Enter”键时,程序甚至不进入$("#search-input").keyup(function (event){
部分。但文本从文本字段中消失,页面似乎重新加载。
我再重复一遍,该问题只能在生产站点上重现。在我上面显示的单独的本地页面上,一切正常。
有谁知道是什么问题?
Update:除 Enter 外,所有按键操作正常。当我按下 Enter 键时,$("#search-input").keyup(function (event){
不运行,就像没有发生任何事件一样。
使用以下处理按“Enter”键的代码解决了该问题:
$("#search-button").on('click', function () {
var theUrl = "/search.aspx?search=" + $('#search-input').val();
window.location = theUrl;
});
$('#search-input').on('keyup', function (e) {
if (e.which == 13)
$("#search-button").trigger('click');
});
该代码内置于$(document).ready
功能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)