我得到了这个自动提取搜索的Jquery代码,上下箭头的键代码非常适合chrome和safari,但是当我点击firefox或IE上的箭头时没有响应。我环顾四周,尝试使用charCode,甚至为“keyCode”添加了一个变量,即e.which或e.keyCode。仍然没有任何反应。
(function($){
$.fn.fsearch = function(){
var $searchInput = $(this);
$searchInput.after('<div id="divResult"></div>');
$resultDiv = $('#divResult');
$searchInput.focus();
$searchInput.addClass('searchi');
$resultDiv.html("<ul></ul>");
$searchInput.keyup(function(e) {
var q=$(this).val();
var keyCode = (window.event) ? e.which : e.keyCode;
if(q != '')
{
var current_index = $('.selected').index(),
$options = $resultDiv.find('.option'),
items_total = $options.length;
// When Down Arrow key is pressed
if (keyCode == 40) {
if (current_index + 1 < items_total) {
current_index++;
change_selection($options,current_index);
}
}
// When Up Arrow is pressed
else if (keyCode == 38) {
if (current_index > 0) {
current_index--;
change_selection($options,current_index);
}
}
// When enter key is pressed
else if(keyCode == 13){
var id = $resultDiv.find('ul li.selected').attr('id');
var name = $resultDiv.find('ul li.selected').find('.name').text();
window.location = "event.listing.php?id="+id;
}
else{
$resultDiv.fadeIn();
// Query search details from database
$.getJSON("json.php",{searchword: q},function(jsonResult)
{
var str='';
for(var i=0; i<jsonResult.length;i++)
{
str += '<li id=' + jsonResult[i].id + ' class="option"><img class="profile_image" src="data:image/jpg;base64,'+jsonResult[i].photo+'" alt="'+jsonResult[i].fullName+'"/><span class="name">' + jsonResult[i].fullName + '</span><br /><span class="name" style="font-size:10px; color:#999;">'+jsonResult[i].tel+'</span></li>';
}
$resultDiv.find('ul').empty().prepend(str);
$resultDiv.find('ul li').first().addClass('selected');
});
$resultDiv.find('ul li').live('mouseover',function(e){
current_index = $resultDiv.find('ul li').index(this);
$options = $resultDiv.find('.option');
change_selection($options,current_index);
});
// Change selected element style by adding a css class
function change_selection($options,current_index){
$options.removeClass('selected');
$options.eq(current_index).addClass('selected');
}
}
}
else{
//Hide the results if there is no search input
$resultDiv.hide();
}
});
// Hide the search result when clicked outside
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if ($clicked.hasClass("searchi") || $clicked.hasClass("searchf")){
}
else{
$resultDiv.fadeOut();
}
});
// Show previous search results when the search box is clicked
$searchInput.click(function(){
var q=$(this).val();
if(q != '')
{
$resultDiv.fadeIn();
}
});
// Select the element when it is clicked
$resultDiv.find('li').live("click",function(e){
var id = $(this).attr('id');
var name = ($(this).find('.name').text());
window.location = "event.listing.php?id="+id;
});
};
})(jQuery);
答案 0 :(得分:1)
你有jQuery标记,所以你应该只使用event.which
:
event.which
属性规范化event.keyCode
和event.charCode
。建议观看event.which
键盘输入键。
var keyCode = e.which;