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 に答える