2013-03-25 60 views
0

我有一個jQuery「自動建議」類型的搜索框。它使用Href填充搜索結果列表,以便用戶可以點擊列表中的項目進入相關頁面。用戶也可以使用箭頭鍵滾動瀏覽列表進行選擇。我現在想要做的是允許用戶按Enter鍵轉到他們選擇的URL。我有Enter鍵的工作,但我不知道我應該如何構建列表或從列表中提取Href等,或者我應該有第二個隱藏的列表,其中只包含純粹的URL?jQuery - 如何使用回車鍵在列表中打開URL

這裏是到目前爲止的代碼與相關章節標記###:

<script> 

var results_list = ''; 

function callback(result) { 
    results_list.show(); 
    var items = []; 
    $.each(result, function (i, item) { 
     items.push("<li><a href='/view/raw/" + item.collection + "/" + item.classname + "/" + item._id + "'>" + item.Title + "</a></li>"); 
    }); 
    results_list.append(items.join('')); 
} 

var list_selected; 
var li = ''; 

$('.search').each(function() { 
    $(this).keyup(function (e) { 
     var search_type = $(this).attr('name'); 
     results_list = $('#' + search_type + '_list'); 
     li = results_list.children(); 
     var key_code = e.keyCode; 
     if ($.inArray(key_code, [37, 38, 39, 40]) > -1) { 
      if (e.which === 40) { 
       if (list_selected) { 
        list_selected.removeClass('selected'); 
        next = list_selected.next(); 
        if (next.length > 0) { 
         list_selected = next.addClass('selected'); 
        } else { 
         list_selected = li.eq(0).addClass('selected'); 
        } 
       } else { 
        list_selected = li.eq(0).addClass('selected'); 
       } 
      } else if (e.which === 38) { 
       if (list_selected) { 
        list_selected.removeClass('selected'); 
        next = list_selected.prev(); 
        if (next.length > 0) { 
         list_selected = next.addClass('selected'); 
        } else { 
         list_selected = li.last().addClass('selected'); 
        } 
       } else { 
        list_selected = li.last().addClass('selected'); 
       } 
      } 
     } else { 
      // ### relevant section ### 
      if (key_code == 13) { // what to do here?? 
       window.location = list_selected.html(); 
      // ### 
      } else { 
       results_list.empty(); 
       var params = { 
        'search_type': search_type, 
         'q': $(this).val() 
       }; 
       if ($(this).val()) { 
        ajaxThis("search_box", params, callback); 
       } 
      } 
     } 
    }); 
}); 

</script> 

回答

1
if (key_code == 13 && $('.selected').length > 0) { // Make sure there's a selection 
    var selected_item = $('li.selected:first a'); // select li and a 

    // Two options: 
    // A.) Make sure the li a's href is an absolute path so you can do: 
    window.location = selected_item.attr('href'); 
    // B.) Keep the relative href, trigger a click on the element: 
    $(selected_item).trigger('click'); 
} 
+0

去與選項1 ..謝謝! – MFB 2013-03-25 23:07:19