2012-07-19 26 views
1

我試圖在jQuery中設置一些簡單的頁面導航。例如,如果用戶按下左箭頭鍵,我希望頁面加載一些東西。直到用戶首先點擊頁面纔開啓jquery keyup

除用戶必須首先單擊瀏覽器窗口才能註冊關鍵事件以外的所有工作。

下面是我使用的代碼:這似乎是一個焦點問題

$(document).ready(function() { 
    $(document.documentElement).live("keyup", function(event) { 
     if (event.keyCode == 37) {//left arrow 
     //do something here 
     } 
    }); 
}); 

,但我讀過,使用document.documentElement意味着我沒有把重點放在什麼特別。

它適用於用戶在頁面上點擊一次,然後點擊左箭頭。但是,如果他們加載頁面並點擊左擊箭頭不會觸發。

有什麼辦法解決這個問題?

+0

瀏覽器的胸圍有焦點,但我敢肯定,不需要點擊(我用的關鍵事件很多,用'$(文件).keydown(')。 – 2012-07-19 17:18:46

+1

['.live()'折舊。使用'.on()'代替。](http://stackoverflow.com/questions/9422069/jquerys-live-is-deprecated-what-do-i-use-現在) – SomeKittens 2012-07-19 17:18:53

+0

'on'在這種情況下是無用的。只需使用'keydown'或'keyup'函數即可。 – 2012-07-19 17:21:07

回答

1

你的頁面沒有focus就可以了,因此你在頁面上輸入need to click。把重點放在一些控制上,然後它就會起作用。住在這種情況下不會造成任何麻煩,但是由於現場情況惡化,開始使用on

我按狀態設置焦點$('#txt1').focus();評論此聲明,你會注意到你將不得不點擊該頁面來獲取keyup事件。

Live Demo

$(document).ready(function() { 
    $('#txt1').focus(); //This is the statement that puts focus on page 
    $(document.documentElement).live("keyup", function(event) { 


     if (event.keyCode == 37) {//left arrow 
     //do something here 
      alert(""); 
     } 
    }); 
});​ 
+0

好吧,我嘗試使用不同的元素對我做.focus()和它的工作。 – user1535082 2012-09-24 16:04:07

3

嘗試使用.on()並且沒有委託事件處理。

$(document).ready(function() { 
    $(document).on("keyup", function(event) { 
     if (event.which == 37) {//left arrow 
     //do something here 
     } 
    }); 
}); 

OR使用.keyup()方法如下圖所示:

$(document).ready(function() { 
    $(document).keyup(function(event) { 
     if (event.which == 37) {//left arrow 
     //do something here 
     } 
    }); 
}); 

在這裏你不需要live(不建議使用)和document.documentElement

+0

我仍然需要用這些方法點擊頁面。 – user1535082 2012-07-19 21:19:50

+0

我正在加載iframe中的頁面,所以也許這就是爲什麼我需要點擊... – user1535082 2012-07-19 21:22:47

0

.live()-function已棄用。試試這個:

$(document).ready(function() { 
    $('body').on("keyup", function(event) { 
     if (event.keyCode == 37) {//left arrow 
     //do something here 
     } 
    }); 
}); 
0

無需使用過時live也不on,因爲你尚未擁有的文件。另外,不需要使用document.documentElement

根本就

$(document).keydown(function(){ 
}); 

這工作得很好,不需要點擊。

相關問題