HTML:
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="button" class="mybutton" value="focus next" onclick="focusNext()">
<input type="button" class="mybutton" value="focus prev" onclick="focusPrev()">
JS代码:
//focused is getting last focused textfield
var focused = null;
$(".mytextbox").focus(function(){
focused = $(this);
});
//focus next
function focusNext(){
$(".mytextbox").each(
//checking is this textbox focused
if($(this)[0] == focused[0]){
$(this).next().focus();
//or
$(this).next(".mytextbox").focus();
}
);
}
//focus prev
function focusPrev(){
$(".mytextbox").each(
//checking is this textbox focused
if($(this)[0] == focused[0]){
$(this).prev().focus();
//or
$(this).prev(".mytextbox").focus();
}
);
}
我认为$(this).next()
不起作用.. next()
函数在每个函数中都不起作用
如何在点击按钮时关注下一个或上一个文本字段? 帮帮我..谢谢..
答案 0 :(得分:5)
在您的脚本中,您有synatx错误,因为.each()
应该有一个函数作为其参数。
除此之外,每个循环都有一个逻辑错误,因为你在循环中调用focus()
,焦点处理程序将被调用并将chage focus
引用的变量,以便下一次迭代也是如此,因此Next
按钮不起作用。
var focused = null;
$(".mytextbox").focus(function () {
focused = $(this);
});
//focus next
function focusNext() {
if (focused && focused.length) {
focused.next('.mytextbox').focus();
}
}
//focus prev
function focusPrev() {
if (focused && focused.length) {
focused.prev('.mytextbox').focus();
}
}
演示:Fiddle
答案 1 :(得分:2)
假设页面加载时默认聚焦第一个输入字段,请参阅下面的代码 -
HTML:将id
用于按钮以绑定点击事件
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input id="nextBtn" type="button" class="mybutton" value="focus next">
<input id="prevBtn" type="button" class="mybutton" value="focus prev">
jQuery:为第一个字段设置焦点。单击下一个或上一个按钮时,检查next或prev元素是否存在,然后相应地设置焦点。
$(function(){
//focus first input fields
$(".mytextbox:first").focus();
var currentFocusedInput = $(".mytextbox:first");
// next button
$("#nextBtn").click(function(){
var nextInputToFocus = currentFocusedInput.next('.mytextbox');
if($(nextInputToFocus).length > 0)
{
currentFocusedInput = $(nextInputToFocus);
}
$(currentFocusedInput).focus();
});
// previous button
$("#prevBtn").click(function(){
var prevInputToFocus = currentFocusedInput.prev('.mytextbox');
if($(prevInputToFocus).length > 0)
{
currentFocusedInput = $(prevInputToFocus);
}
$(currentFocusedInput).focus();
});
});
<强> JSFiddle Demo 强>