我正在寻找一种方法来消毒输入,我粘贴到浏览器,这是可能的用jQuery做吗?
到目前为止,我已经想出了这个:
$(this).live(pasteEventName, function(e) {
// this is where i would like to sanitize my input
return false;
}
不幸的是,我的发展因为这个“小”问题而戛然而止。 如果有人能给我指出正确的方向,我真的会让我成为一个快乐的露营者。
我正在寻找一种方法来消毒输入,我粘贴到浏览器,这是可能的用jQuery做吗?
到目前为止,我已经想出了这个:
$(this).live(pasteEventName, function(e) {
// this is where i would like to sanitize my input
return false;
}
不幸的是,我的发展因为这个“小”问题而戛然而止。 如果有人能给我指出正确的方向,我真的会让我成为一个快乐的露营者。
当前回答
监听粘贴事件并设置一个keyup事件监听器。在keyup上,捕获值并删除keyup事件监听器。
$('.inputTextArea').bind('paste', function (e){
$(e.target).keyup(getInput);
});
function getInput(e){
var inputText = $(e.target).val();
$(e.target).unbind('keyup');
}
其他回答
该方法使用jqueries contents().unwrap()。
First, detect the paste event Add a unique class to the tags that are already in the element into which we are pasting. After a given timeout scan through all the contents unwrapping tags that don't have the class that you set earlier. Note: This method does not remove self closing tags like See an example below. //find all children .find('*') and add the class .within .addClass("within") to all tags $('#answer_text').find('*').each(function () { $(this).addClass("within"); }); setTimeout(function() { $('#answer_text').find('*').each(function () { //if the current child does not have the specified class unwrap its contents $(this).not(".within").contents().unwrap(); }); }, 0);
嗯…我认为你可以使用e.clipboardData来捕捉被粘贴的数据。如果不成功,看看这里。
$(this).live("paste", function(e) {
alert(e.clipboardData); // [object Clipboard]
});
请看这个例子:http://www.p2e.dk/diverse/detectPaste.htm
它本质上用oninput事件跟踪每个更改,然后通过字符串比较检查它是否是粘贴。哦,在IE中有一个onpaste事件。所以:
$ (something).bind ("input paste", function (e) {
// check for paste as in example above and
// do something
})
$("#textboxid").on('input propertychange', function () {
//perform operation
});
它会工作得很好。
监听粘贴事件并设置一个keyup事件监听器。在keyup上,捕获值并删除keyup事件监听器。
$('.inputTextArea').bind('paste', function (e){
$(e.target).keyup(getInput);
});
function getInput(e){
var inputText = $(e.target).val();
$(e.target).unbind('keyup');
}