2011-12-12 82 views
15

我有以下的html:选择next()的输入

<div> 
    <input type="text" maxlength="2" class="day-spin-month"></input> 
    <span>/</span> 
    <input type="text" maxlength="2" class="day-spin-day"></input> 
    <span>/</span> 
    <input type="text" maxlength="4" class="day-spin-year"></input> 
</div> 

我试图将焦点更改到下一个输入。我有以下两种方式。

$('.day-spin-month').on('keyup', function() { 
    if (this.value.length >= 2) { 
     $(this).next().next().focus(); 
    } 
}); 
$('.day-spin-day').on('keyup', function() { 
    if (this.value.length >= 2) { 
     $(this).next().next().focus(); 
    } 
}); 

小提琴:http://jsfiddle.net/dan_vitch/JbQaN/1/

$('.day-spin-month').on('keyup', function() { 
    if (this.value.length >= 2) { 
     var test=$(this).next() 
     var test2= $(test).next('input'); 
     test2.focus(); 
    } 
}); 
$('.day-spin-day').on('keyup', function() { 
    if (this.value.length >= 2) { 
     var test=$(this).next() 
     var test2= $(test).next('input'); 
     test2.focus(); 
    } 
}); 

小提琴:http://jsfiddle.net/dan_vitch/JbQaN/2/

但它不以这种方式工作:

$('.day-spin-month').on('keyup', function() { 
    if (this.value.length >= 2) { 
     $(this).next('input').focus(); 
    } 
}); 
$('.day-spin-day').on('keyup', function() { 
    if (this.value.length >= 2) { 
     $(this).next('input').focus(); 
    } 
}); 

小提琴:http://jsfiddle.net/dan_vitch/rJwyE/2/

我想使用不工作的方式。我不确定它的选择器是否不正确,或者我理解下一步的方法()

+0

http://stackoverflow.com/questions/290535/best-way-to-find-next-form-input-element-在-的jQuery –

回答

46

.next()仅查看DOM中的下一个同级元素。 IE浏览器。

$('.day-spin-month').next('input'); 

因为下一个兄弟是跨度而不是输入,所以不会匹配任何东西。

nextAll()着眼于所有未来的兄弟姐妹,所以你想:

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