jquery keypress iterate through each loop?
hey guys, probably a simpel question, however couldn't find anything online.
i have a list with search results and i want to be able to navigate through the list with my up and down keys.
开发者_C百科 if (e.keyCode == 40) { //down
//alert('down');
$('#searchresults ul li').each(function() {
});
}
if (e.keyCode == 38) { //up
//alert('up');
}
if (e.keyCode == 13) { //enter
//alert('enter');
}
the searchresults look like this:
<ul>
<li class="matched"><a href="link1">link1</a></li>
<li class="matched"><a href="link2">link2</a></li>
<li class="matched"><a href="link3">link3</a></li>
</ul>
So basically i just want to be able to navigate through my searchresults with the up and down keys. the selection of the current element should maybe just change the background color and when i press enter the linked and matched element is fired.
any idea how i can iterate through the searchresults? thank you
edit:
var pressedCount = 0;
if (e.keyCode == 40) { //down
console.log(pressedCount);
$('#searchresults ul li').index(pressedCount).addClass('selected');
pressedCount++;
}
does not work, because i'm doing something wrong with the index-method. However the pressedCount var increments on every arrowkeydown trigger.
Working demo: http://jsfiddle.net/zBjrS/1/
(You have to click the page first, in order to focus the IFRAME.)
Not sure that I really like the idea of taking over a users arrow keys, especially when we live in a world that page up/down is no longer present on a lot of keyboards(notebooks). There are a lot of users that use arrows for scrolling.
If you are set on keyboard nav on your results, just set the focus on the first link, then Tab will go down and Shift+tab will go up.
All this functionality is already built in you just have to set the focus on the first element
$('first_element_selector').focus();
something like this should work
if (e.keyCode == 40) { //down
$('#searchresults ul li').each(function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
$(this).next().addClass('selected');
// use $(this).prev() for UP case
}
});
}
note that you would need to preload the list with a 'selected' css class or add in some code to apply the selected to the first item in the list if none had been selected
also you will need code to check if you are on the last item in the list, you will not want to call .next() in this case
jQuery next http://api.jquery.com/next/
jQuery prev http://api.jquery.com/prev/
jQuery hasClass http://api.jquery.com/hasClass/
jQuery removeClass http://api.jquery.com/removeClass/
精彩评论