I am using jquery in one of my projects. I have a scenario where I have to add keyboard events to the td cells of a table to move up and down in them. I was able to achieve this using the following code.
Here is my code:
<script type="text/javascript">
var tds = jQuery("#myTable td");
tds.bind('keyup', function(event){
var key = event.which;
moveSelection(key, jQuery(this), tds);
event.preventDefault();
});
function moveSelection(key, current_td, all_tds){
var index = parseInt(current_td.attr("id"));
if (key == 13) { //Enter Key
current_td.click();
} else if(key == 38) { //Page Up Key
if(all_tds[index - 1]){
all_tds[index - 1].focus();
}
} else if(key == 40) { //Page Down Key
if(index < all_tds.length){
var next_index = index + 1;
if(next_index < all_tds.length){
all_tds[index + 1].focus();
}
}
}
}
I was able to move through the td cells if the page has no scroll bars. But when the page has scroll bars, when I use PageUp/PageDown keys two things happen.
- My page scrolls up/down based on the key pressed.()
- The respective td selec开发者_如何学编程tion moves/up based on the key pressed.
In the first case, it might be because of the events are bound to the page as well as my table tds. How can I prevent this. I dont want my page to scroll when I am dealing with my table. I tried a lot but failed. Looking here for some help.
Any help greatly appreciated.. Thanks in advance...
try to add an "return false" at each key handle. or this one:
if(event.stopPropagation) {
event.stopPropagation(); // standard browsers
} else {
event.cancelBubble = true; // IE
}
精彩评论