我目前正在尝试在单击按钮后添加文本区域。然而,虽然按钮点击有效,但文本区域没有注册任何按键事件。
注意:有一个不同文件的列表,这就是为什么我在其 id 上附加一个唯一的 id。
$(".add").click(function() {
var id = $(this).attr("id");
$("#" + id).after("<textarea placeholder = 'Add a description for this piece of work. Press enter to save it.' class = 'edit-work' id = 'edit-work" + id + "'></textarea>");
$("textarea").not("#edit-work"+id).remove();
});
$(".edit-work").on('keypress', function(e) {
alert('foo');
});
最佳答案
当您将 keypress
监听器绑定(bind)到文本区域时,文本区域不存在。您需要将按键绑定(bind)到文档(或现有的父级)
$(document).on('keypress', ".edit-work", function(e){
alert('foo');
});
有关事件委托(delegate)的更多信息 here :
关于javascript - jQuery 按键不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35143219/