我有以下 html 页面:
<form action="editProfile" id="userInformation">
<fieldset id="birthdate">
<label><input type="text" id="day" maxlength="2"/>/<input type="text" id="month" maxlength="2"/>/<input type="text" id="year" maxlength="2"/>
</fieldset>
<fieldset>
<label>Name</label><input type="text" id="name"/>
</fieldset>
</div>
现在我想总是跳到下一个输入字段。 我试过:
$("#birthdate input[type=text]").keyup(function(e){
if($(this).val().length == $(this).attr('maxlength')){
$(this).next(":input").focus();
}
});
但这似乎仍在字段集中。 nextall 似乎不起作用,或者我使用错误。
编辑: 到目前为止我的解决方案:
if($(this).val().length == $(this).attr('maxlength')){
if($(this).parent().children().last().attr('id') == $(this).attr("id")){
$(this).parent().next().find(':input').focus();
}else{
$(this).next("input").focus();
}
}
请您参考如下方法:
这是使用自定义方法的解决方案(工作示例:http://jsfiddle.net/jamiec/uQdSS/)
(function($) {
$.fn.nextOrParentNext = function(sel){
var $next = $(this).next(sel);
if($next.length)
{
return $next;
}
else
{
var $nextParent = $(this).parent().next().find(sel);
if($nextParent.length)
{
return ($nextParent);
}
}
};
})(jQuery);
$("#birthdate input:text").keydown(function(e){
if($(this).val().length == $(this).attr('maxlength')){
$(this).nextOrParentNext(":input").focus();
}
});
基本上,自定义插件包装了 if/else 逻辑,使其成为字段集中的最后一项。
