问题
I have an input of type text that is used to perform asynchronous table row searches using jquery. I have an .on function attached to the search input and on key down, I'm calling a function called hoverDown(). What I would like to happen when the down arrow key is pressed, is to hover over the table rows. And when a table row is hovered over with the arrow key, and the user hits enter, I would like for the href to fire and take the user to that related page. I am able to detect the e.keyCode but that's about as far as I've been able to get and I really don't know where to take it from here. Relevant Code:
//HTML
<div id="main">
<input type="text" class="table-search" id="search" autocomplete="off" placeholder="Search Clients…">
<table class="table" id="tblData">
<thead><tr><th>Name</th> <th>Title</th></tr></thead>
<tbody>
<tr><td><a href="http://lar.loc/cases">Scott</a></td> <td>Client</td></tr>
<tr><td><a href="http://lar.loc/cases">Billy</a></td><td>Client</td></tr>
<tr><td><a href="http://lar.loc/cases">George</a></td><td>Client</td></tr>
<tr><td><a href="http://lar.loc/cases">Sara</a></td><td>Client</td></tr>
<tr><td><a href="http://lar.loc/cases">John</a></td><td>Client</td></tr>
<tr><td><a href="http://lar.loc/cases">Megan</a></td><td>Client</td></tr>
<tr><td><a href="http://lar.loc/cases">Ben</a></td><td>Client</td></tr>
<tr><td><a href="http://lar.loc/cases">Jully</a></td><td>Client</td></tr>
<tr><td><a href="http://lar.loc/cases">Bethany</a></td><td>Client</td></tr><tr><td><a href="http://lar.loc/cases">Alen</a></td><td>Client</td></tr>
<tr><td><a href="http://lar.loc/cases">Jane</a></td><td>Client</td></tr>
<tr><td><a href="http://lar.loc/cases">Alice</a></td><td>Client</td></tr></tbody></table>
</div>
//javascript
$(document).ready(function(){
$("#main").on("keydown", "#search", function(e){
hoverDown();
});
});
function hoverDown()
{
if ($(document).keydown()) {
$(document).keydown(function(e){
if (e.keyCode == 40) {
alert("down");
e.keyCode = null;
}
if (e.keyCode == 38) {
alert("up");
e.keyCode = null;
}
});
};
}
回答1:
I threw together a fiddle for you to play around with http://jsfiddle.net/7BcZA/2/
Summary:
When you "hover" a row, add a class to it. Mine is called selected
. This identifies that it's selected, as well as adds CSS styling. Remove the class selected
from the previous tr
that was selected.
Get the next or previous tag based on which was button was pressed.
As a bonus, I added the "press enter" functionality that you were looking for =)
.
来源:https://stackoverflow.com/questions/14927751/how-can-i-make-the-up-and-down-arrow-keys-navigate-a-tables-rows-and-programma