我有一个完全由javascript创建的表,而我的Jquery代码不想使用它:/如果我在手动创建的表上使用它(html格式),我就能正常工作。请参见下面的小提琴。
仅供参考,这段jquery代码应该只允许用户使用箭头键在输入(表单元格)之间导航
这就是jsFiddle
我将脚本加载到head中:
<head>
<meta charset="UTF-8">
<title>My Page</title>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/js.js"></script>
</head>表在这里创建(在body中):
<div id="myTable">
</div>
<script type="text/javascript">
createTable();
addPerson(1);
</script>这是我的jQuery:
$(document).ready(function() {
$('input').keydown(function(e) {
if (e.keyCode == 40 || e.keyCode == 13) {
var thisClass = $(this).parent().attr('class');
$(this).parent().parent().next('tr').children('.' + thisClass).children().focus();
}
});
$('input').keydown(function(e) {
if (e.keyCode == 39) {
$(this).parent().next('td').children('input').focus();
}
});
$('input').keydown(function(e) {
if (e.keyCode == 38) {
var thisClass = $(this).parent().attr('class');
$(this).parent().parent().prev('tr').children('.' + thisClass).children().focus();
}
});
$('input').keydown(function(e) {
if (e.keyCode == 37) {
$(this).parent().prev('td').children('input').focus();
}
});
});发布于 2017-01-23 04:40:36
您只能将事件侦听器连接到现有元素。您应该将其连接到文档,以处理动态创建的元素:
$(document).on('keydown', 'input', function(e) {
// keycode first
if (e.keyCode==40 || e.keyCode==13) {
}
// keycode second etc.
if (e.keyCode==39) {
}
if (e.keyCode==38) {
}
if (e.keyCode==37) {
}
});UPD实际上,如果文档非常大,将listener连接到文档并不是一个好主意。您可以在创建元素后将侦听器附加到该元素。
发布于 2017-01-23 04:38:53
您可能试图在创建表之前绑定keydown事件。请尝试使用on方法。
您还需要将事件附加到创建表之前已存在的现有父元素,如body或另一个父元素中。
$('body').on('keydown', "input", function(e) {
if (e.keyCode==40 || e.keyCode==13) {
var thisClass = $(this).parent().attr('class');
$(this).parent().parent().next('tr').children('.'+thisClass).children().focus();
}
});以此为例。我建议您使用另一个包装元素,并通过它的class或id进行绑定,而不是使用元素名称。
https://stackoverflow.com/questions/41795849
复制相似问题