我的 javascript 遇到了一些问题,希望您能提供帮助。
我使用这里的示例:http://www.knowlbase.in/2012/01/traverse-cursor-through-text-box-with.html在页面上的文本框之间移动。向左和向右效果很好,但向上和向下将光标向右对 Angular 移动(但是,当按下向上键时,它会向上对 Angular 移动,按下向下键时,它会向下对 Angular 移动)。
谁能看出我哪里出错了?
编辑-添加jsFiddle
这就是我所拥有的:
function arrowKeyPressed() {
$('input').keyup(function (e) {
if (e.which == 39)
$(this).closest('td').next().find('input').focus();
else if (e.which == 37)
$(this).closest('td').prev().find('input').focus();
else if (e.which == 40)
$(this).closest('tr').next().find('td:eq(' + $(this).closest('td').index() + ')').find('input').focus();
else if (e.which == 38)
$(this).closest('tr').prev().find('td:eq(' + $(this).closest('td').index() + ')').find('input').focus();
});
};
这就是我添加文本框属性的方式(所有文本框都是以编程方式创建的):
tb.Attributes.Add("onkeyup", "arrowKeyPressed()");
生成后的 HTML 如下所示(这只是一个文本框;除选项卡索引外,其他所有框都相同):
<input name="ctl00$MainContent$addPrices$Textbox101"
type="text"id="ctl00_MainContent_addPrices_Textbox101" tabindex="13"
onblur="validateText('ctl00_MainContent_addPrices_Textbox101',
'ctl00_MainContent_addPrices_AddQuote', 'ctl00_MainContent_addPrices_msgLbl')"
style="width:60px;">
有什么想法吗?
谢谢!
最佳答案
问题在于您的 HTML 无效。 <th />
仅允许在 <thead />
中元素。
因此,如果您替换 <th />
第一列的标签为 <td />
效果很好。
<tr>
<td>2013 04 Apr</td>
<td>
<input style="width:60px;">
</td>
<td>
<input style="width:60px;">
</td>
<td>
<input style="width:60px;">
</td>
<td>
<input style="width:60px;">
</td>
<td>
<input style="width:60px;">
</td>
<td></td>
</tr>
<!-- ... -->
编辑
“错误”行为的原因是 <th />
但为了完整起见,我将详细说明原因。
$(this).closest('td').index()
这决定了 <td />
的索引在行中(包括 <th />
)。
您用于构建仅查找 <td />
的选择器的该索引元素。
'td:eq(' + $(this).closest('td').index() + ')'
所以您“丢失”了第一列 ( <th />
)。
关于javascript - 无法使用箭头键在文本框之间移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16013081/