我正在寻找一种方法来消毒输入,我粘贴到浏览器,这是可能的用jQuery做吗?

到目前为止,我已经想出了这个:

$(this).live(pasteEventName, function(e) {
 // this is where i would like to sanitize my input
 return false;
}

不幸的是,我的发展因为这个“小”问题而戛然而止。 如果有人能给我指出正确的方向,我真的会让我成为一个快乐的露营者。


当前回答

该方法使用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);

其他回答

我通过使用以下代码修复了它:

$("#editor").live('input paste',function(e){
    if(e.target.id == 'editor') {
        $('<textarea></textarea>').attr('id', 'paste').appendTo('#editMode');
        $("#paste").focus();
        setTimeout($(this).paste, 250);
    }
});

现在我只需要存储插入符号的位置并附加到该位置,然后我就全部设置好了……我认为:)

实际上,您可以直接从事件中获取值。不过如何到达它有点迟钝。

如果你不想让它通过,则返回false。

$(this).on('paste', function(e) {

  var pasteData = e.originalEvent.clipboardData.getData('text')

});

这离你想要的越来越近了。

function sanitize(s) {
  return s.replace(/\bfoo\b/g, "~"); 
};

$(function() {
 $(":text, textarea").bind("input paste", function(e) {
   try {
     clipboardData.setData("text",
       sanitize(clipboardData.getData("text"))
     );
   } catch (e) {
     $(this).val( sanitize( $(this).val() ) );
   }
 });
});

请注意,当clipboardData对象没有找到时(在IE以外的浏览器上),你目前得到的是元素的完整值+剪贴板的值。

你可以做一些额外的步骤来区分这两个值,在输入之前和输入之后,如果你真的只是在真正粘贴到元素的数据之后。

document.addEventListener('paste', function(e){
    if(e.clipboardData.types.indexOf('text/html') > -1){
        processDataFromClipboard(e.clipboardData.getData('text/html'));
        e.preventDefault();

        ...
    }
});

进一步指出:

剪贴板API和事件

好吧,正好碰到了同样的问题。我绕了很长的路

$('input').on('paste', function () {
  var element = this;
  setTimeout(function () {
    var text = $(element).val();
    // do something with text
  }, 100);
});

只是一个小的超时,直到.val() func可以填充。

E.