Javascript OnPaste
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10972954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript OnPaste
提问by Jake
I have this right now:
我现在有这个:
<input type="text" placeholder="Paste text" onPaste="alert(this.value);">
<input type="text" placeholder="Paste text" onPaste="alert(this.value);">
This does infact work, except, it returns a blank alert window. I don't get any value. Help?
这确实有效,只是它返回一个空白的警报窗口。我没有任何价值。帮助?
回答by Fabrício Matté
The onpasteevent fires before the input's valueis changed. You need something such as a setTimeout:
该onpaste事件在input'svalue更改之前触发。你需要一些东西,比如setTimeout:
<input type="text" placeholder="Paste text" onPaste="var e=this; setTimeout(function(){alert(e.value);}, 4);">?
I'm storing a reference to thisinside a global var as thisis not accessible inside the scope of a timeout function which is attached to the window object.
我this在一个全局this变量中存储了一个引用,因为它在附加到 window 对象的超时函数的范围内是不可访问的。
I'm using 4 miliseconds as the Timeout as it's the minimum valid Interval/Timeout in the HTML5 specification. Edit:As noted in the comments, you may also use 0miliseconds as timeOut which is automatically recalculated to 4. jsPerf tests.
我使用 4 毫秒作为超时,因为它是 HTML5 规范中的最小有效间隔/超时。编辑:如评论中所述,您也可以使用0毫秒作为超时,它会自动重新计算为4. jsPerf 测试。
You may as well use a function call inside your onpasteevent passing thisas a parameter to prevent your HTML mixing with JS too much. :)
你也可以在你的onpaste事件中使用一个函数调用this作为参数来防止你的 HTML 与 JS 混合太多。:)
And here's a function easier to read and which you can use in multiple inputs:
这是一个更易于阅读的函数,您可以在多个输入中使用它:
function pasted(element) {
setTimeout(function(){
alert(element.value);
}, 0); //or 4
}?
Which can be called with simply onPaste="pasted(this)"for any input.
可以简单地onPaste="pasted(this)"为任何输入调用它。
回答by Dmitry Pashkevich
This is because the onpasteevent fires beforethe content gets pasted into the element (link) so it's not there yet at the time you handle it.
这是因为onpaste事件在内容粘贴到元素 ( link)之前触发,因此在您处理它时它还不存在。
Modern browsers support methods of obtaining clipboard data inside the event handler. Refer to JavaScript get clipboard data on paste event (Cross browser)for cross-browser solution attempts.
现代浏览器支持在事件处理程序中获取剪贴板数据的方法。有关跨浏览器解决方案的尝试,请参阅JavaScript 在粘贴事件(跨浏览器)上获取剪贴板数据。
Also, you can always work around your issue by simply starting a timer in the event handler function (10ms should be enough) that would check your input value later.
此外,您始终可以通过简单地在事件处理函数中启动一个计时器(10 毫秒应该足够)来解决您的问题,以便稍后检查您的输入值。

