2013-07-10 39 views
0

如果我有一個鏈接並希望綁定鍵盤快捷鍵,我應該怎麼做?這似乎並沒有工作:製作捕鼠器點擊鏈接

<a id="next" href="/next/page">Next page</a> 
<script src="mousetrap.js"></script> 
<script> 
    Mousetrap.bind("n", function() { 
    document.getElementById("next").click(); 
    }); 
</script> 

回答

0

有幾個原因,我相信你的代碼是不工作,因爲我不是一個JS專家;我只是從我的小經驗中說出這一點。

  • 您假設有爲定位標記定義的onClick函數。即使它是 - 你還沒有定義在onclick函數中發生了什麼。

  • 您應該使用外部函數來實現相同;所以有效地使用可以點擊的錨標籤以及當用戶按下「N」時也將用戶帶到期望頁面的功能。

我試過把我的想法變成一個小小的解決方案;請看下面的內容,看看你是否可以弄清楚你可能會出錯的地方。我會讓一些更有經驗的JS告訴你什麼是錯的,爲什麼它不工作。

<html> 
<head> 
<title>mouse trap test</title> 
</head> 
<body> 
    <a id="next" href="next/page">Next page</a> 
<script src="mousetrap.js"></script> 
<script> 

function GoToLocation(url) 
    { 
    //window.location = "http://www.stackoverflow.com"; 
    window.location = url; 
    } 

    Mousetrap.bind("n", function() { 
    //alert('N pressed' + document.getElementById("next").href); 
    //document.getElementById("next").click(); 
    GoToLocation(document.getElementById("next").href); 
    }); 


</script> 
</body> 
</html> 

我希望上面的幫助。

0

是否有一個特定的原因,你需要點擊鏈接?像這樣的東西會替你工作嗎?

Mousetrap.bind("n", function() { 
    window.location.href = "/next/page"; //Or document.getElementById('next').href as in Robert's response. 
}); 

而且,這可能會幫助:How do I programmatically click on an element in JavaScript?