tymeJV的評論讓我思考如何方便它實際上是在我的情況我會使用以下僞代碼輸入元素的keyup事件:
define a var named foo
if key is down arrow
set foo to the next sibling of the current row
else if key is up arrow
set foo to the previous sibling of the current row
otherwise
abort
define a var named bar
if current input is the first input in the current row
set bar to the first input in foo
else if current input is second input in the current row
set bar to the second input in foo
otherwise
abort
set focus to bar
我可能已經發布了問題太早了,但我希望它對未來的其他人有用。
謝謝。
編輯:我還沒有時間去測試(甚至寫信,哈哈),直到今天。我會在下面發佈我的最終代碼,以防有人發現它有用。
的Javascript:
// obj - the source element
// event - the event data
// i - child index of the textbox
function form_vert_nav(obj, event, i) {
var o = ((event.keyCode == 38 || event.keyCode == 40) ? obj.parentNode.parentNode : null);
if (event.keyCode == 38) { // up
o = o.previousSibling;
} else if (event.keyCode == 40) { // down
o = o.nextSibling;
} else {
return;
}
if (o == null) {
// keyCode wasn't 38 or 40 and magically slipped through the else,
// or the sibling simply doesn't exist (more likely).
return;
}
if ((o = o.getElementsByTagName(obj.tagName)[i]) == null) {
// 404 Element Not Found
return;
}
o.focus();
}
HTML:
<tbody>
<tr>
<td><input type='text' onkeydown='form_vert_nav(this, event, 0);'/></td>
<td><input type='text' onkeydown='form_vert_nav(this, event, 1);'/></td>
</tr>
<tr>
<td><input type='text' onkeydown='form_vert_nav(this, event, 0);'/></td>
<td><input type='text' onkeydown='form_vert_nav(this, event, 1);'/></td>
</tr>
<tr>
<td><input type='text' onkeydown='form_vert_nav(this, event, 0);'/></td>
<td><input type='text' onkeydown='form_vert_nav(this, event, 1);'/></td>
</tr>
</tbody>
你會監視按鍵事件,如果該鍵碼的向下或向上箭頭一致,關注下輸入線。 – tymeJV 2014-10-03 15:53:47
如果'input'元素不在同一個'tr'中,我該怎麼做? – 0x47686F7374 2014-10-03 15:59:30
DOM遍歷 - 可能會更容易與jQuery(我知道它說沒有外部庫,但嘿) – tymeJV 2014-10-03 16:00:47