javascript - 无法使用箭头键在文本框之间移动

标签 javascript jquery

我的 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>
<!-- ... -->

updated fiddle

编辑
“错误”行为的原因是 <th />但为了完整起见,我将详细说明原因

$(this).closest('td').index()

这决定了 <td /> 的索引在行中(包括 <th /> )。 您用于构建仅查找 <td /> 的选择器的该索引元素。

'td:eq(' + $(this).closest('td').index() + ')'

所以您“丢失”了第一列 ( <th /> )。

关于javascript - 无法使用箭头键在文本框之间移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16013081/

相关文章:

javascript - multer 的唯一目的是将主体对象和文件对象添加到请求对象吗?编辑和保存应该由不同的包来完成吗?

javascript - 当选择任何文件时,文件上传按钮上的 jQuery 监听器

javascript - 尝试调用另一个对等点时出现 PeerJS 错误 : Failed to execute 'addStream' on 'RTCPeerConnection' : parameter 1 is not of type 'MediaStream'

java - 无法使用 Selenium WebDriver (Firefox) 与输入(角色=组合框)交互

jQuery:获取 DIV 的确切位置(以像素为单位),而不是返回 "auto"作为结果

javascript - 如何在 .ready() 期间更改文档的标题?

javascript - 如何使用javascript或html打开手机chrome浏览器

php - 案例, "document.ready"阻塞时

jQuery:删除多个<select>的所有元素的函数?

javascript - Google ReCaptcha前端解决方案