2

我目前正在通过 .click 事件添加一个输入,然后想要收听此输入上发生的任何按键。但是,附加的在插入后不会触发任何事件(即模糊、按键、焦点)。有没有人有什么建议?提前致谢!

$("#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();
});

我也尝试过 .keyup .keydown ,但它们不起作用。

4

4 回答 4

7

您的keypress处理程序仅被添加到您添加它时存在的元素中。

live无论何时添加,您都需要调用该方法将其添加到与选择器匹配的每个元素中。

例如:

$("input").live('keypress', function(e){
    var inputStr = $(this).html();
    $("#inputCopier").text(inputStr);
    var newWidth = $("#inputCopier").innerWidth;
    $(this).css("width", newWidth);
});
于 2009-12-31T00:07:26.577 回答
5

为了捕获blur/focus事件,为什么不在将创建的元素添加到 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 ()
    ;
});
于 2009-12-31T01:54:50.947 回答
1

回应您的评论:

如您所见,该live方法不支持该blur事件。

作为一种解决方法,您可以在每次添加元素时手动添加处理程序,如下所示:

$("#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();
        });
});
于 2009-12-31T01:33:19.990 回答
0

你可以试试

$("input").live("keypress", function (e) { 
    alert(e.keyChar);
});
于 2009-12-31T00:07:37.823 回答