给jsrender模板内numeric-input输入框绑定keyup事件失效求助
解决JsRender动态生成输入框的箭头导航事件绑定问题
问题说明
在JsRender模板中定义了带numeric-input类的输入框,尝试绑定keyup事件实现箭头导航(左右上下切换输入框焦点)。页面加载日志正常输出,但在输入框内按键无任何响应。
模板代码:
<script type="text/x-jsrender" id="js-true-up-location-items-list-template"> <input name="actualSalesCount" id="actual-sales-count-input-{{:id}}" class="numeric-input" type="text" value="{{:actualSalesCount}}" data-id="{{:id}}"> </script>
原绑定代码:
window.onload = function () { console.log("Page has been loaded"); $(document).ready(function () { console.log('enabling arrow navigation from the page!'); $('.numeric-input').keyup(function (e) { console.log('keyup!'); if (e.which == 39) { // right arrow $(this).closest('td').next().find('input').focus(); } else if (e.which == 37) { // left arrow $(this).closest('td').prev().find('input').focus(); } else if (e.which == 40) { // down arrow $(this).closest('tr').next().find('td:eq(' + $(this).closest('td').index() + ')').find('input').focus(); } else if (e.which == 38) { // up arrow $(this).closest('tr').prev().find('td:eq(' + $(this).closest('td').index() + ')').find('input').focus(); } }); }); };
问题根源
- 动态元素事件绑定失效:JsRender模板渲染的输入框是页面加载完成后动态生成的,原代码直接用
$('.numeric-input').keyup()只能绑定初始DOM中已存在的元素,动态生成的元素不会继承该事件绑定。 - 冗余的DOM加载监听嵌套:
window.onload和$(document).ready都是监听DOM加载完成的事件,嵌套使用完全没必要,反而可能导致绑定时机延迟(window.onload需等待所有资源加载完成,比$(document).ready触发更晚)。
解决方法
使用事件委托(Event Delegation),将事件绑定到已存在的父元素(如document或输入框的直接父容器),利用事件冒泡机制捕获动态元素的事件。同时清理冗余的DOM加载监听嵌套。
修改后的绑定代码:
$(document).ready(function () { console.log('enabling arrow navigation from the page!'); // 事件委托:绑定到document,监听所有带numeric-input类元素的keyup事件 $(document).on('keyup', '.numeric-input', function (e) { console.log('keyup!'); 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) { // 下箭头 const currentTdIndex = $(this).closest('td').index(); $(this).closest('tr').next().find(`td:eq(${currentTdIndex})`).find('input').focus(); } else if (e.which == 38) { // 上箭头 const currentTdIndex = $(this).closest('td').index(); $(this).closest('tr').prev().find(`td:eq(${currentTdIndex})`).find('input').focus(); } }); });
额外优化点
- 提取重复的
$(this).closest('td').index()为变量,提升代码可读性与性能 - 改用模板字符串拼接选择器,比传统字符串拼接更清晰
- 若知道输入框的直接父容器(如某表格ID),可将事件委托绑定到该父容器而非
document,减少事件冒泡层级,提升性能:$('#your-table-id').on('keyup', '.numeric-input', function(e) { // 事件处理逻辑 });
内容的提问来源于stack exchange,提问作者arielcr
相关产品推荐
相关产品推荐

