2009-12-31 179 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