2013-03-08 37 views
1

我想在具有焦點的錶行上按鍵時調用java腳本函數。下面是代碼,但是當我按下Enter鍵時,腳本函數沒有被調用。爲處理焦點行處理onkeypress事件

http://jsfiddle.net/sirishkumar/58FZG/19/

<input id="test" type="text"> 
<table> 
    <tr onkeypress="return openLog(e,'row 1')"> 
     <td>Row 1</td> 
    </tr> 
    <tr onkeypress="return openLog(e,'row 2')"> 
     <td>Test</td> 
    </tr> 
</table> 


var j = jQuery; 
var currentRow = 0; 
var pagesize = 2; 

function ChangeCurrentRow() { 
    var tableRow = document.getElementsByTagName("tr")[(currentRow % pagesize)]; 
    tableRow.focus(); 
    j(tableRow).siblings().removeClass("highlight-row"); 
    j(tableRow).addClass("highlight-row"); 
} 

j(document).ready(function() { 
    j('#test').val("Ready"); 
    ChangeCurrentRow(); 

}); 

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

    if (e.keyCode == 38) { 
     currentRow--; 
     ChangeCurrentRow(); 
     return false; 
    } 
    if (e.keyCode == 40) { 
     currentRow++; 
     ChangeCurrentRow(); 
     return false; 
    } 
}); 


function openLog(e, id) { 

    if (e.keyCode == 13) { 
     $('#input').text(id) 
    } 

    return true; 
} 
+0

你確定你使用了正確的keyCode嗎?我檢查了一下,keydown事件實際上是在發射。 – sweetamylase 2013-03-08 09:31:37

+0

是http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes。 – Poorna 2013-03-08 09:36:11

+0

@sweetamylase如何在Firebug中查看關鍵事件?您是否使用不同的工具 – Poorna 2013-03-08 09:39:01

回答

0

沒有 「重點」 的行。你的focus()什麼都不做。只是嘗試寫:

j(tableRow).focus(function(){alert('test');}); 
tableRow.focus(); 

你會看到什麼=) 嘗試在$(document).keypress()處理按鍵事件,並做選擇行操作。 onkeypress爲tr - 什麼都不做(除了contenteditable="true" tr)。

+0

我完全不理解你的評論。所以你說在聚焦行中沒有意義,並且Enter鍵事件不會被髮送到聚焦元素。這是爲什麼? – Poorna 2013-03-08 13:57:09

+0

@Sirish我不知道爲什麼,對不起。我只寫了上面的代碼來測試關注「tr」標籤,並且「onfocus」事件沒有被解僱。 – 2013-03-08 17:25:53