jQuery .keypress在动态添加的输入上 [英] Jquery .keypress on a dynamically added input

查看:94
本文介绍了jQuery .keypress在动态添加的输入上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在通过.click事件添加输入,然后希望收听此输入上发生的任何按键.但是,附件在插入后不会触发任何事件(即模糊,按键,聚焦).有没有人有什么建议?预先感谢!

I am currently adding an input via a .click event and then wanting to listen to any keypress that occurs on this input. However, the appended isn't firing any events after it is inserted (i.e. blur, keypress, focus). Does anyone have any suggestions? Thanks in advance!

$("#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,它们不起作用.

I did try .keyup .keydown as well, they don't work.

推荐答案

为了捕获blur/focus事件,为什么不在将处理程序添加到创建的元素之前将其添加到DOM?

In order to capture blur/focus events, why not add the handler to the created element before adding it to 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 ()
    ;
});

这篇关于jQuery .keypress在动态添加的输入上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆