我有一个jQuery搜索脚本,它使用on keyup函数提交查询。如何在用户按Enter键时进行搜索?
这是我目前的代码:
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query+'&page=1';
window.location.hash='search/'+query+'/1/';
document.title=$(this).val()+" - My Search Script";
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
$("#result").html(response);
}
});
});
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
});
答案 0 :(得分:1)
#search_form必须是<form>
的ID!
$(document).ready(function(){
$("#search_form").submit(function(){
var search=$("#search").val();
var query=encodeURIComponent(search);
var yt_url='search.php?q='+query+'&page=1';
window.location.hash='search/'+query+'/1/';
document.title=search+" - My Search Script";
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
$("#result").html(response);
}
});
});
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
});
答案 1 :(得分:1)
我发现我需要这样做,有2个事件,一个适合输入键,另一个忽略按键:
jQuery('#search').keydown(function (e) {
if (e.which == 13) {
// Do you work here
}
});
jQuery('#search').keypress(function (e) {
if (e.which == 13) {
return false;
}
});
答案 2 :(得分:0)
一般情况下
$(document).keyup(function( e ) {
if (e.keyCode == 13) {
// execute your code
}
});