Javascript OnPaste [英] Javascript OnPaste
问题描述
我现在有这个:
< input type =textplaceholder =粘贴文字onPaste =alert(this .value);>
这确实有效,除了它返回一个空白的警报窗口。我没有任何价值。帮助?
This does infact work, except, it returns a blank alert window. I don't get any value. Help?
推荐答案
onpaste
事件在<$ c $之前触发c>输入的值
已更改。你需要一些东西,比如 setTimeout
:
The onpaste
event fires before the input
's value
is changed. You need something such as a setTimeout
:
<input type="text" placeholder="Paste text" onPaste="var e=this; setTimeout(function(){alert(e.value);}, 4);">
我在中存储对
this
的引用,因为在超时范围内无法访问此
附加到窗口对象的函数。
I'm storing a reference to this
inside a global var as this
is not accessible inside the scope of a timeout function which is attached to the window object.
我使用4毫秒作为超时,因为它是HTML5规范中的最小有效间隔/超时。 修改:如评论中所述,您还可以使用 0
miliseconds作为timeOut,自动重新计算为 4
。 jsPerf测试 。
I'm using 4 miliseconds as the Timeout as it's the minimum valid Interval/Timeout in the HTML5 specification. As noted in the comments, you may also use 0
miliseconds as timeOut which is automatically recalculated to 4
. jsPerf tests.
您也可以在 onpaste
事件中使用函数调用此作为一个参数,以防止你的HTML与JS混合太多。 :)
You may as well use a function call inside your onpaste
event passing this
as a parameter to prevent your HTML mixing with JS too much. :)
这里的函数更易于阅读,可以在多个输入中使用:
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
}
只需 onPaste =粘贴(此)
任何输入。
这篇关于Javascript OnPaste的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!