2012-02-25 53 views
2

我:如何在按下按鍵時使用JavaScript加載新頁面?

<a id="nextPage" href="somepage.php?name=foo">Next Page</a> 

當有人按下鍵盤上的箭頭按鈕,我想將用戶重定向到包含在定位代碼中href。我怎樣才能做到這一點與JavaScript/jQuery的?

我的想法是這樣的:

window.location = $('#nextPage').attr('href'); 

有什麼想法?

+0

閱讀http://api.jquery.com/click/ – 2012-02-25 00:30:41

+0

當我按下箭頭鍵時,我希望我的瀏覽器在瀏覽器窗口中滾動頁面。 – 2012-02-25 00:31:06

+1

@Yaypaul - 他問的是按鍵,而不是鼠標點擊。 – 2012-02-25 00:32:07

回答

3
$(document).on('keydown', function (event) {alert(event.type); 
    if (event.which == 37) { 
     $('#prevPage').trigger('click'); 
     //or 
     window.location = $('#prevPage').attr('href'); 
    } else if (event.which == 39) { 
     $('#nextPage').trigger('click'); 
     //or 
     window.location = $('#nextPage').attr('href'); 
    } 
});​ 

這裏是一個演示:http://jsfiddle.net/jasper/VprbW/2/

您也可以訪問這樣的鏈接之一的href屬性執行速度更快:

window.location = document.getElementById('nextPage').href; 
相關問題