简体   繁体   中英

jQuery keypress is not working

I'm currently trying to add a textarea after a button is clicked. However, although the button click works, the textarea does not register any keypress events.

NOTE: There is a list of different files which why I attach a unique id to its 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');
}); 

when you bind the keypress listener to the textarea, the textarea doesn't exist. You need to bind the keypress to the document (or an existing parent)

$(document).on('keypress', ".edit-work", function(e){
    alert('foo');
});

More info on event delegation here :

$(".edit-work").on('keypress', ...) will only register the handler on currently existing .edit-work elements. If you add a new one, it will not have a handler attached. It's like telling all your employees not to produce any paper documentation, then hiring someone new without telling him anything, then wondering why he's doing the traditional office stuff with paper.

You want the live handler: $(editWorkAncestor).on('keypress', '.edit-work', ...) , with editWorkAncestor being a document , or any node under which your .edit-work will appear (or a selector for one such). This will attach the handler to the ancestor, which will check each time if the event target matches the provided live selector.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM