2011-06-18 106 views
1

我有一個jQuery搜索腳本,它使用on keyup函數來提交查詢。如何在用戶按下回車鍵時進行搜索?從jQuery搜索腳本中刪除keyup

這裏是我當前的代碼:

$(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

在一般的情況下

$(document).keyup(function(e) { 
     if (e.keyCode == 13) { 
      // execute your code 
     } 
    }); 
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

我發現,我需要做到這一點,有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; 
       } 
      });