jquery不能在桌面上创建javascript
问题描述:
我有我完全由javascript创建的表和我的jquery代码不想使用它︰/如果我使用它创建manualy(在html中)表上我工作得很好。看下面的小提琴。jquery不能在桌面上创建javascript
FYI这个jQuery代码应该只是alow用户使用箭头键输入之间的导航(表格单元格)
这里是jsFiddle
我打开我的脚本头:
<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>
此处创建表格(在主体中):
<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();
}
});
});
答
您只将事件侦听器连接到现有元素。你应该将它连接到文件处理动态创建的元素:
$(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实际上它是一个坏主意,听者连接到一个文件,如果它是非常大的。您可以在创建元素后将侦听器附加到元素。
答
你可能试图创建表之前的绑定事件。请尝试使用on
方法。
您还需要将事件附加到创建表之前存在的现有父元素,例如在正文或其他父元素中。
$('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();
}
});
以此为例。我建议你使用另一个包装元素,并通过它的类或id绑定,而不是元素名称。
你为什么用这么多听众?只使用一个。 –
感谢它现在的作品。我使用这么多的听众,因为我是不好的程序员;)感谢这一点,我会修复它,当我学习如何:) – Hovadko
看看更新的答案。 –