0

テキスト入力があり、それに注目すると、「#number_list」の最初の「.option」が「.selected」になります。機能を作成したい - keybord の Up または Down キーが押されたときに、「number_list」の次または前の要素が「選択された」クラスをグランド化し、現在の要素がこのクラスを失った場合。

<input type="text" name="number" id="number" maxlength="30" />

<div id="number_list">
  <div class='option selected'>aaa</div>
  <div class='option'>bbb</div>
  <div class='option'>ccc</div>
</div>

http://jsfiddle.net/YNyEr/

「.option」要素の配列を作成し、現在の要素をインデックスで取得しようとしましたが、これを行う方法が見つかりません。では、どうすればそれができるのでしょうか? また、jQuery 1.5.1 を使用しています。

4

2 に答える 2

1

この手っ取り早い実装はどうですか:http://jsfiddle.net/zerkms/YNyEr/2/

var $input = $('#some_number'),
    current_index = $('.selected').index(),
    $number_list = $('#number_list'),
    $options = $number_list.find('.option'),
    items_total = $options.length;

$input.val(current_index);

$input.bind('keyup', function(e) {
    if (e.keyCode == 40) {
        if (current_index + 1 < items_total) {
            current_index++;
            change_selection();
        }
    } else if (e.keyCode == 38) {
        if (current_index > 0) {
            current_index--;
            change_selection();
        }
    }
});

function change_selection()
{
    $options.removeClass('selected');
    $options.eq(current_index).addClass('selected');
    $input.val(current_index);
}​
于 2012-05-21T09:15:05.377 に答える
-1

javascriptイベントのonkeyupとonkeydownを確認する必要があると思います。idによる選択で遊ぶ場合、それは非常に簡単なはずです、

例えば

<div onkeydown='document.getElementById("nextid").className += "selected";this.className -= "selected";' class='option'>bbb</div>
于 2012-05-21T09:01:17.473 に答える