Jquery .keypress 动态添加的输入
我当前正在通过 .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 ,但它们不起作用。
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();
});
I did try .keyup .keydown as well, they don't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的
keypress
处理程序只会添加到您添加它时存在的元素中。您需要调用
live
方法将其添加到每个与选择器匹配的元素,无论它何时添加。例如:
Your
keypress
handler is only being added to the elements that exist when you added it.You need to call the
live
method to add it to every element that matches the selector, no matter when it was added.For example:
为了捕获
blur
/focus
事件,为什么不在将创建的元素添加到 DOM 之前将处理程序添加到它呢?In order to capture
blur
/focus
events, why not add the handler to the created element before adding it to DOM?回应您的评论:
正如您所注意到的,
live
方法不支持blur
事件。作为解决方法,您可以在每次添加元素时手动添加处理程序,如下所示:
In response to your comment:
As you noticed, the
live
method does not support theblur
event.As a workaround, you could manually add the handler every time you add an element, like this:
你可以尝试
you could try