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

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

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

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


当前回答

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

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以外的浏览器上),你目前得到的是元素的完整值+剪贴板的值。

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

其他回答

这段代码为我工作,要么从右击粘贴或直接复制粘贴

   $('.textbox').on('paste input propertychange', function (e) {
        $(this).val( $(this).val().replace(/[^0-9.]/g, '') );
    })

当我粘贴第1节:劳动力成本时,它在文本框中变成1。

为了只允许浮动值,我使用这段代码

 //only decimal
    $('.textbox').keypress(function(e) {
        if(e.which == 46 && $(this).val().indexOf('.') != -1) {
            e.preventDefault();
        } 
       if (e.which == 8 || e.which == 46) {
            return true;
       } else if ( e.which < 48 || e.which > 57) {
            e.preventDefault();
      }
    });

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

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

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

请看这个例子: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
        });

它会工作得很好。

为了跨平台兼容性,它应该处理oninput和onpropertychange事件:

$ (something).bind ("input propertychange", function (e) {
    // check for paste as in example above and
    // do something
})