JQuery .on(“keydown”)附加到页面时不起作用 [英] JQuery .on("keydown") Not Working When Appended To Page
本文介绍了JQuery .on(“keydown”)附加到页面时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个侧边菜单,您可以右键单击并选择重命名。这从< li>< / li>
中删除了< a href =...
添加一个输入字段。我似乎没有这个附加的输入做任何事情,但似乎我可以使这个工作的输入尚未附加。
I have a side menu of which you can right-click and choose to rename. This removed the <a href="...
from the <li></li>
and adds an input field. I cannot seem to have this appended input do anything however it seems I can get this to work on inputs of which have not been appended.
$('.ShowInput').click(function(e) {
$('body').html("<input type='text' value='search' class='search'>");
});
$("input").on("keydown",function search(e) {
if(e.keyCode == 13) {
alert($(this).val());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="ShowInput">
Click to show input
</div>
推荐答案
尝试绑定密钥将事件向下发送到祖先元素,并将您的输入与搜索类作为参数传递给 .on()
方法。
Try binding your keydown event to an ancestor element, and pass your input with the search class as an argument to the .on()
method.
$("body").on("keydown", "input.search", function (e) {
var inputValue = $(this).val();
if(e.keyCode == 13) {
alert(inputValue);
}
});
这篇关于JQuery .on(“keydown”)附加到页面时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文