Jquery .keypress on a dynamically added input

2019-02-11 03:48发布

问题:

I am currently adding an input via a .click event and then wanting to listen to any keypress that occurs on this input. However, the appended isn't firing any events after it is inserted (i.e. blur, keypress, focus). Does anyone have any suggestions? Thanks in advance!

$("#recipientsDiv").click(function(){
    $(this).append('< input type="text" id="toInput" class="inlineBlockElement" style="border:0px none #ffffff; padding:0px; width:20px; overflow:hidden;" />')
    $("#toInput").focus();
});
$("input").keypress(function(e){
    var inputStr = $(this).html();
    $("#inputCopier").text(inputStr);
    var newWidth = $("#inputCopier").innerWidth;
    $(this).css("width", newWidth);
});
$("#toInput").blur(function(){
    $("#toInput").remove();
});

I did try .keyup .keydown as well, they don't work.

回答1:

In order to capture blur/focus events, why not add the handler to the created element before adding it to DOM?

$('#recipientsDiv').click (function() 
{
    $('< input type="text" id="toInput" class="inlineBlockElement" style="border:0px none #ffffff; padding:0px; width:20px; overflow:hidden;" />')
        .keypress (function (e) { ... })
        .blur (function (e) { $(this).remove () })
        .appendTo ($(this))
        .focus ()
    ;
});


回答2:

Your keypress handler is only being added to the elements that exist when you added it.

You need to call the live method to add it to every element that matches the selector, no matter when it was added.

For example:

$("input").live('keypress', function(e){
    var inputStr = $(this).html();
    $("#inputCopier").text(inputStr);
    var newWidth = $("#inputCopier").innerWidth;
    $(this).css("width", newWidth);
});


回答3:

In response to your comment:

As you noticed, the live method does not support the blur event.

As a workaround, you could manually add the handler every time you add an element, like this:

$("#recipientsDiv").click(function(){
    $(this).append('< input type="text" id="toInput" class="inlineBlockElement" style="border:0px none #ffffff; padding:0px; width:20px; overflow:hidden;" />')

    $("#toInput")
        .focus()
        .blur(function(){
            $("#toInput").remove();
        });
});


回答4:

you could try

$("input").live("keypress", function (e) { 
    alert(e.keyChar);
});