簡體   English   中英

選擇下一個(不是立即)輸入標簽

[英]Selecting the next (not immediately) input tag

如果我有三個由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();
    }
});

jQuery .next()方法:

獲取匹配元素集中每個元素的緊隨其后的兄弟。 如果提供了選擇器,則僅當它與該選擇器匹配時,它才會檢索下一個兄弟。

這是因為.next()方法返回緊隨其后的兄弟元素。 由於緊接着的兄弟是一個span ,所以沒有選擇任何東西。

一種選擇是使用.nextAll()方法 然后鏈.first()以選擇第一個匹配:

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

更新的示例

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

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

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

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

您還可以使用.siblings()來查找與其同級的輸入:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM