是否可以使用setTimeout()函数来粘贴文本?

是否可以使用setTimeout()函数来粘贴文本?

问题描述:

我发现当使用鼠标粘贴文本(即 Hello )时,以下函数将抛出一个空的弹出窗口:

I found out that when pasting text (i.e. Hello) by using the mouse, the following function will throw an empty popup:

$('input:text').onpaste = function()
{
    alert($('input:text').val());
});

事情是,当onpaste事件被触发时,文本还没有实际粘贴到输入栏(至少是我的猜测)。因此,将功能更改为:

The thing is, when the onpaste event is being fired, the text is not yet actually pasted to the input field (at least that's my guess). So changing the function to:

$('input:text').onpaste = function()
{
    setTimeout(function()
    {
        alert($('input:text').val()
    }, 100);
}

通过显示文本 Hello 的弹出窗口提供正确的结果粘贴到输入字段。

gives a correct result by showing a popup with the text Hello when pasted to the input field.

现在我的问题是:是否有可能抓住粘贴的文本,而不使用 setTimeout()函数?这个变通方法似乎很脏,所以我很乐意不用使用它。

Now my question: is there is any possibility to catch the pasted text without using the setTimeout() function? This workaround seems quite dirty so I'd love to not have to use it.

kkthxbai
xon1c

kkthxbai xon1c

可以使用 oninput 事件,现代浏览器支持此方法

you can use the oninput event instead, modern browsers support this method

http://jsfiddle.net/pxfunc/KDLjf/

$('input').bind('input', function(e) {
    console.log($(this).val());
});