2013-08-01 53 views
1

我正在一個內部的web應用程序,並希望添加鍵盤導航到它。從研究來看,某種形式的javascript似乎是解決這個問題的最佳方式。從特定輸入文本框jQuery的鍵盤導航

這裏是什麼,我想出了一個例子:

$(document).keydown(function (e) { 

       if (e.keyCode == 74) { 
        window.location = 'page1.html'; // Key = J 
       } 
       else if (e.keyCode == 75) { 
        window.location = 'page2.html'; // Key = k 
       } 
       else if (e.keyCode == 76) { 
        window.location = 'page3.html'; // Key = L 
       } 

      }); 

這工作得很好,但我想,使其只能從1個特定的文本輸入的可執行文件。 (基本上是一個導航盒)我一直沒能弄清楚這一部分。有任何想法嗎?

有沒有人有這種導航形式的經驗。它可靠嗎?

我對JavaScript並不是很有經驗,所以任何想法或建議都會受到讚賞。

+0

我認爲jQuery的.focus()函數可能是你所需要的 - > http://api.jquery.com/focus/ – reekogi

+2

或者你可以使用'e.target'來檢查你的領域,或者你可以將'keydown'函數附加到該字段而不是文檔。 – putvande

回答

4

假設你的導航輸入框是這樣

<input id="nav" type="text"/> 

然後使用相同的處理此輸入元素

$("#nav").keydown(function (e) { 

       if (e.keyCode == 74) { 
        window.location = 'page1.html'; // Key = J 
       } 
       else if (e.keyCode == 75) { 
        window.location = 'page2.html'; // Key = k 
       } 
       else if (e.keyCode == 76) { 
        window.location = 'page3.html'; // Key = L 
       } 

      }); 
0

您應該將事件綁定到特定領域做到這一點。 事情是這樣的:

$('#yourinputfieldid').on('keydown',function (e) { 
    if (e.keyCode == 74) { 
     window.location = 'page1.html'; // Key = J 
    } else if (e.keyCode == 75) { 
     window.location = 'page2.html'; // Key = k 
    } else if (e.keyCode == 76) { 
     window.location = 'page3.html'; // Key = L 
    } 
}); 
0

首先建議,據我知道e.which代替e.keyCode的使用。

$('#id_of_input').on('keydown',function(e){...}); 

$(document).on('keydown','#id_of_input',function(e){}); 

當元素動態添加到頁面時,應該使用第二個元素。

1
$(document).keydown(function (e){ 

     if(e.target.id !== "elementId"){ 
      return; 
     } 

     if (e.keyCode == 74) { 
      window.location = 'page1.html'; // Key = J 
     } 
     else if (e.keyCode == 75) { 
      window.location = 'page2.html'; // Key = k 
     } 
     else if (e.keyCode == 76) { 
      window.location = 'page3.html'; // Key = L 
     } 
    });