[英]Intercept Paste data in JavaScript
I got the following code from Intercept paste event in Javascript . 我从Javascript中的Intercept paste事件中获取了以下代码。
I need to get it before it is pasted, otherwise i lose the "\\n" characters i need to save. 我需要在粘贴之前得到它,否则我会丢失我需要保存的“\\ n”字符。
It works great to intercept clipboard data for one element with an id. 它可以很好地拦截具有id的一个元素的剪贴板数据。 I need it to work on all input elements.
我需要它来处理所有输入元素。 When I try to use jQuery to get the input elements nothing.
当我尝试使用jQuery来获取输入元素时。
Any help is appreciated. 任何帮助表示赞赏。
var paster = function () {
var myElement = document.getElementByTagName('pasteElement');
myElement.onpaste = function(e) {
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else if (e.clipboardData && e.clipboardData.getData) {
pastedText = e.clipboardData.getData('text/plain');
}
processExcel(pastedText); // Process and handle text...
return false; // Prevent the default handler from running.
};
}
Just add a paste
event listener to the document. 只需向文档添加
paste
事件侦听器即可。
document.addEventListener("paste", function (e) {
console.log(e.target.id);
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else if (e.clipboardData && e.clipboardData.getData) {
pastedText = e.clipboardData.getData('text/plain');
}
e.preventDefault();
e.target.value = "You just pasted '" + pastedText + "'";
return false;
});
What nmaier said, but you also need to check for the original event. nmaier说了什么,但你还需要检查原始事件。
document.addEventListener("paste", function (e) {
console.log(e.target.id);
var pastedText = undefined;
if (window.clipboardData && window.clipboardData.getData) { // IE
pastedText = window.clipboardData.getData('Text');
} else {
var clipboardData = (e.originalEvent || e).clipboardData;
if (clipboardData && clipboardData.getData) {
pastedText = clipboardData.getData('text/plain');
}
e.preventDefault();
e.target.value = "You just pasted '" + pastedText + "'";
return false;
}
});
Also, you should probably add the event listener just to the element, instead of the whole document. 此外,您应该只将事件侦听器添加到元素,而不是整个文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.