2015-03-25 57 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 
    }); 
相關問題