2015-03-25 58 views
1

如果我有span标记分隔的三个输入标签,这样选择下一个(不是立即)输入标签

<input class="some-class" type="number" maxlength="4"> 
<span class="bull">&bull;</span> 
<input class="some-class" type="number"maxlength="4"> 
<span class="bull">&bull;</span> 
<input class="some-class" type="number" maxlength="4"> 

如何选择才能做一些使用jQuery的下一个输入标签?我的jQuery代码以下不使用.next()功能

$(':input').keyup(function (e) { 
    if ($(this).val().length == $(this).attr('maxlength')) { 
     $(this).next(':input').focus(); 
    } 
}); 

回答

1

jQuery .next() method:

选择下一个输入标签获取紧随其后的每个元素的兄弟在匹配的元素。如果提供了一个选择器,只有当它与该选择器匹配时才会检索下一个兄弟。

这是因为.next()方法返回紧随其后的兄弟元素。由于紧接着的兄弟姐妹是span,所以没有选择任何东西。

一种选择是使用.nextAll() method代替。

$(this).nextAll(':input').first().focus(); 

Updated Example

$(':input').keyup(function (e) { 
    if (this.value.length == $(this).attr('maxlength')) { 
     $(this).nextAll(':input').first().focus(); 
    } 
}); 
1

您可以使用.index().eq()方法:

var $inputs = $(':input'); 

$inputs.keyup(function(e) { 
    if (this.value.length == this.getAttribute('maxlength')) 
     $inputs.eq($inputs.index(this) + 1).focus(); 
}); 
1

您还可以使用.siblings(当时为了选择第一个匹配连锁.first() ),找到兄弟姐妹的输入:

$(':input').keyup(function(e){ 
    if($(this).val().length==$(this).attr('maxlength')) 
    $(this).siblings('input').focus(); 
    // do something 
    }); 
相关问题