問題描述
我似乎無法找到如何完成此任務的答案,但這是我多次看到的功能.本質上,我是在呼應一個列表,我想創建使用箭頭鍵/輸入突出顯示和選擇這些項目的能力.有人可以幫助我了解如何實現這一目標嗎?我知道如何使用鍵碼(當然),只是不知道如何將其變成功能代碼以選擇列表中的項目...
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.
推薦答案
由于您沒有真正解釋您遇到的問題,我只是創建了一個通用解決方案.希望這會有所幫助:
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/
這篇關于使用箭頭鍵瀏覽列表?(JavaScript/JQ)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!