Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

jquery - Navigate through list using arrow keys? (JavaScript/JQ)

I can't seem to find an answer to how to accomplish this, yet it's a feature I've seen several times. Essentially I'm echoing out a list and I would like to create the ability to highlight and select these items using arrow keys/enter. Can someone help give me an idea as to how I can accomplish this? I know how to use keycodes (of course), just not how to turn that into functioning code for selecting items on a list...

I was thinking maybe I'd have to have some sort of hidden radio button to mark it as selected or not... but even then I don't know how I would jump from one radio button to the other up and down the list. So if anyone could give me a hand with this I'd really appreciate it. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you didn't really explain what you're having trouble with, I just created a general solution. Hopefully this helps:

var li = $('li');
var liSelected;
$(window).keydown(function(e) {
    if(e.which === 40) {
        if(liSelected) {
            liSelected.removeClass('selected');
            next = liSelected.next();
            if(next.length > 0) {
                liSelected = next.addClass('selected');
            } else {
                liSelected = li.eq(0).addClass('selected');
            }
        } else {
            liSelected = li.eq(0).addClass('selected');
        }
    } else if(e.which === 38) {
        if(liSelected) {
            liSelected.removeClass('selected');
            next = liSelected.prev();
            if(next.length > 0) {
                liSelected = next.addClass('selected');
            } else {
                liSelected = li.last().addClass('selected');
            }
        } else {
            liSelected = li.last().addClass('selected');
        }
    }
});

JSFiddle: http://jsfiddle.net/Vtn5Y/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...