Jquery .keypress 动态添加的输入

Posted

技术标签:

【中文标题】Jquery .keypress 动态添加的输入【英文标题】:Jquery .keypress on a dynamically added input 【发布时间】:2010-12-31 06:59:08 【问题描述】:

我目前正在通过 .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 ,但它们不起作用。

【问题讨论】:

【参考方案1】:

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

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

例如:

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

【讨论】:

这对按键很有用,谢谢!但是,它似乎不适用于模糊。根据文档,它不受支持...有什么建议吗? 在附加到 DOM 之前将处理程序添加到元素 - 请参阅下面的答案【参考方案2】:

为了捕获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 ()
    ;
);

【讨论】:

在复杂的场景中我可以做什么,例如当我们想要动态添加多个元素时?似乎更好的方法是使用委托事件处理,例如 On() 。【参考方案3】:

回应您的评论:

如您所见,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();
        );
);

【讨论】:

谢谢,效果很好!抱歉回复晚了,圣诞假期:-D【参考方案4】:

你可以试试

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

【讨论】:

以上是关于Jquery .keypress 动态添加的输入的主要内容,如果未能解决你的问题,请参考以下文章

jQuery 自动完成 KEYUP vs KEYPRESS vs KEYDOWN

jquery datatable搜索框添加按钮,改变keypress搜索为点击按钮搜索

jQuery 如果没有,则将 http:// 作为前缀添加到文本输入

jquery.filer 编辑模式动态文件添加

“Keypress”事件无法正常工作,使用 jQuery 和 Select2

如何检测keypress()上输入的第一个字符