如何在粘贴事件期间获取字段的值? [英] How to get the value of a field during the paste event?
问题描述
我有一个文本字段,我将粘贴
事件绑定到使用JQuery。当我第一次将某些东西粘贴到表单字段并记录其 val()
时,它返回一个空字符串。同样,如果我再次粘贴到字段中,它会在粘贴之前返回先前的值。基本上我有一个竞争条件或排序问题,因为缺乏一个更好的术语。在粘贴事件完成之前,表单字段似乎不会更新。
I have a text field that I'm binding the paste
event to using JQuery. When I first paste something into the form field and log its val()
it returns a blank string. Likewise, if I paste again into the field, it returns the previous value before pasting. Essentially I have a race condition or sequencing issue, for lack of a better term. It seems the form field will not update until the paste event completes.
是否有任何方法可以在粘贴后检查字段的值事件已完成,实际填充了该字段?我想要实际的字段值,而不是clipboardData,因为我知道这是一个仅限IE的功能。
Is there any way to check the value of the field after the paste event has completed and the field is actually populated? I want the actual field value, not the clipboardData, as I know that's an IE-only feature.
$('#url').bind('paste', function(e) {
alert($(this).val());
});
推荐答案
事实证明,一个不错的解决方案是包装回调在 setTimeout()
中,延迟为0毫秒,以使其异步。
It turns out a decent solution is to wrap the callback in a setTimeout()
, with a delay of 0 milliseconds, in order to make it asynchronous.
我的新代码是:
var urlField = $('#url');
urlField.bind('paste', function(e) {
setTimeout(function() {
alert(urlField.val());
}, 0); // note the 0 milliseconds
});
感谢 DigitalBush的Masked Input Plugin ,它在整个源代码中使用了这种技术。
Thanks to DigitalBush's Masked Input Plugin, it uses this technique throughout the source.
这篇关于如何在粘贴事件期间获取字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!