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

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

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

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


当前回答

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

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

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

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

});

其他回答

这里有一个警告。在Firefox中,如果您重置每个键上的输入文本,如果文本长于输入宽度允许的可视区域,则重置每个键上的值将破坏浏览器自动将文本滚动到文本末尾的插入号位置的功能。相反,文本将滚动回开始,而插入符号则不在视图中。

function scroll(elementToBeScrolled) 
{
     //this will reset the scroll to the bottom of the viewable area. 
     elementToBeScrolled.topscroll = elementToBeScrolled.scrollheight;
}

请看这个例子: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
})
document.addEventListener('paste', function(e){
    if(e.clipboardData.types.indexOf('text/html') > -1){
        processDataFromClipboard(e.clipboardData.getData('text/html'));
        e.preventDefault();

        ...
    }
});

进一步指出:

剪贴板API和事件

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

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

   $('.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();
      }
    });