2009-12-31 181 views
2

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

$("#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以及他们不工作。

回答

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() 
    ; 
}); 
+0

我可以在复杂的情况下做些什么,例如当我们想动态添加多个元素时?看来更好的方法是使用委托事件处理,如On()。 – QMaster 2014-02-07 13:04:03

7

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

您需要调用live方法将其添加到与选择器匹配的每个元素,而不管它何时添加。

例如:

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

这对按键非常好,谢谢!但是,它似乎不适用于模糊。根据文件不支持... 有什么建议吗? – BinarySolo00100 2009-12-31 00:56:45

+0

在追加到DOM之前添加处理程序到元素 - 请参阅我的回答下面的 – 2009-12-31 01:55:23

0

你可以尝试

$("input").live("keypress", function (e) { 
    alert(e.keyChar); 
}); 
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(); 
     }); 
}); 
+0

谢谢,这工作得很好!对不起,迟到的回应,圣诞假期:-D – BinarySolo00100 2010-01-05 17:37:20