0

基本上我有这个选择列表,其中包含多个选项:

<select name="drop1" id="Select1" size="30">
  <?php
    for($i = 0;$i<30;$i++)
    {
       echo "<option id=\"other\" value=\"" . $i . "\"></option>\n";
    }
  ?>
</select>

我还有一个输入字段:

<input type="text" id="inputfield"></input>

使用 jquery,我想完成以下任务:每当输入字段被聚焦并按下向上箭头时,我想在选择列表中向上移动 1 个选项。与向下箭头相同。我已经找到了使用哪些 jquery 事件来了解何时按下和向上键:

$('#inputfield').keydown(function(e){ //When a key is pressed..
    var code = (e.keyCode ? e.keyCode : e.which);
    if ((e.keyCode || e.which) == 40) // on key down
    {
       // Make selection go down here       
    }           
    if((e.keyCode || e.which) == 38) // on key up
    {
    // Make selection go up here
    }
});
4

2 回答 2

0

我建议如下:

$('#inputfield').keydown(function(e) { //When a key is pressed..
    var code = (e.keyCode ? e.keyCode : e.which),
        select = document.getElementById('Select1');
    if (code == 38) // on pressing: ↑
    {
        select.selectedIndex = select.selectedIndex + 1;
    }
    else if (code == 40) // on pressing ↓
    {
        select.selectedIndex = select.selectedIndex - 1;
    }
});

JS 小提琴演示

更新以响应 OP 留下的评论(下):

.change()当我使用向上键和向下键方法时,选择列表的事件没有响应。

为了触发change事件,只需使用trigger(); also, in the following code, I've added sanity checks to try and ensure that the key-up/key-down will only happen, and therefore only trigger a changeevent, when the selectoption's selected option can actually change:

$('#inputfield').keydown(function(e) { //When a key is pressed..
    var code = (e.keyCode ? e.keyCode : e.which),
        select = document.getElementById('Select1'),
        current = select.selectedIndex,
        last = $(select).find('option:last').index();
    if (code == 38 && current < last) // on key down
    {
        select.selectedIndex = current + 1;
        $(select).trigger('change');
    }
    else if (code == 40 && current > 0) // on key up
    {
        select.selectedIndex = current - 1;
        $(select).trigger('change');
    }
});​

JS 小提琴演示

于 2012-07-20T18:47:12.613 回答
0
$('#inputfield').on('keydown',function(e) {
    if (e.keyCode === 40) // on key down
    {
       $('select#Select1').find("option:selected").next().attr("selected", true);
    } else if(e.keyCode === 38) // on key up
    {
       $('select#Select1').find("option:selected").prev().attr("selected", true);
    }
});
于 2012-07-20T18:51:22.710 回答