2014-02-05 52 views
0

假设我连续有大约20个下拉菜单,并希望在用键盘更改值后自动跳转到下一个下拉菜单。这个怎么做? 我发现onchange事件只在下拉菜单失去焦点时才会触发(如onblur)。所以我尝试了onkeydown,但这看起来非常不稳定和越野车。如何在值更改后跳转到下一个下拉菜单?

这是我的尝试:

<script> 
function keydown(dd, e) { 
    console.log(dd.value) 
    jumptonext(dd); 
} 
function getNext(current) { 
    var all = document.querySelectorAll('select[onkeydown]'); 
    for (var i = 0; i < all.length; i++) { 
     if (all[i] == current && all[i+1]) return all[i+1]; 
    } 
    return all[0]; 
} 
function jumptonext(current) { 
    var next = getNext(current); 
    next.focus(); 
} 
</script> 
<select onkeydown="keydown(this, event)"> 
    <option></option> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
</select> 

<select onkeydown="keydown(this, event)"> 
    <option></option> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
</select> 

<select onkeydown="keydown(this, event)"> 
    <option></option> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
</select> 

<select onkeydown="keydown(this, event)"> 
    <option></option> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
</select> 

但你可以在控制台中看到日志的值是不正确的。

有没有办法使用键盘更改下拉列表的值,然后跳转到下一个下拉列表并执行相同操作?

+1

你为什么要这个?如果我使用键盘,那么当我切换时不希望它跳跃,因为我可以使用向下箭头在选项之间切换。完成后,我将按[Tab]进入下一个选项。 – David

+0

因为我的老板就是这样想的。我对这个决定并不满意,但他想要这样做,所以我必须这么做 - 不知何故。 – user2881493

+0

好吧,试着向他解释缺乏功能。如果不是,你尝试了键控吗? – David

回答

0

设置一些间隔函数,它检查所有选择的当前值,例如,周期为10ms。如果其中一个值已更改 - 请查看它是什么,并将焦点移至下一个选择。

// define array of current values 
var values = new Array(); 

// here fill it with values of your selects 

setInterval(function(){ 
    // here check if some value was changed 
    // if there is one changed 
    // set the new value into array as a current one 
    // jump to next select with .focus() 
},10); 

我觉得这对于老板来说应该够了。

也许你还需要.blur()当前的(只是一个猜测)。

对不起,但似乎它是唯一的丑陋的方式来做到这一点。

0

你可以通过jquery来处理它。

我将它用于“标签”按。

$('body').on('keydown', 'input, select, textarea', function(e) { 
var self = $(this) 
    , form = self.parents('form:eq(0)') 
    , focusable 
    , next 
    ; 

$('.dropBpx').change(function(){ 

    focusable = form.find('input,a,select,button,textarea').filter(':visible'); 
    next = focusable.eq(focusable.index(this)+1); 
    if (next.length) { 
     next.focus(); 
    } else { 
     form.submit(); 
    } 
    return false; 

}); 

});

我认为这是可以的这个代码买你需要做一些改变。

相关问题