我的目的是当按钮触发 mouseup
事件时将焦点移动到下一个输入元素,这是脚本:
var cleared = false;
$(document).ready(function(){
//focus on first element
var focused = null;
$(".inp").focus(function () {
focused = $(this);
}).first().focus();
//when mousedown, set value 4
$("#btn").mousedown(function(e) {
focused.val("4");
}).mouseup(function(e) {
//when mouseup, change bg color
focused.css("background-color","yellow");
//and focus on next element
if (focused && focused.length) {
focused.next(".inp").focus();
}
});
});
这是我的 html 元素:
<table>
<tr>
<td>ABC</td>
<td><input class="inp"/></td>
<td><input class="inp"/></td>
<td><input class="inp"/></td>
</tr>
</table>
<button id="btn">4</button>Good
我的问题是焦点永远不会设置到下一个,我该如何解决这个问题?
最佳答案
<强> Working fiddle
next() :Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
您在类 inp
中没有“紧随其后的 sibling ” ,所以你必须向上移动一次到父td
然后使用 next()
移动到下一个 td函数,然后在这个 td 中找到类 inp
并执行对焦。
只需替换:
focused.next(".inp").focus();
作者:
focused.parent().next().find(".inp").focus();
完整的 JS :
var cleared = false;
$(document).ready(function(){
//focus on first element
var focused = null;
$(".inp").focus(function () {
focused = $(this);
}).first().focus();
//when mousedown, set value 4
$("#btn").mousedown(function(e) {
focused.val("4");
}).mouseup(function(e) {
//when mouseup, change bg color
focused.css("background-color","yellow");
//and focus on next element
if (focused && focused.length) {
focused.parent().next().find(".inp").focus();
}
});
});
希望这有帮助。
关于javascript - 单击按钮聚焦于下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32414347/