2013-03-08 48 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