2015-09-27 61 views
4

我试过了(jsfiddle),但它不起作用。使用jQuery粘贴后删除空格

如何看到警报为空。这就像.val()函数在字符串被复制之前启动。

$(document).on('paste', '#pasteIt', function(){ 
    alert($("#pasteIt").val()); 
    var withoutSpaces = $("#pasteIt").val(); 
    withoutSpaces = withoutSpaces.replace(/\s+/g, ''); 
    $("#pasteIt").text(withoutSpaces); 
}); 

为什么?

回答

6

获取剪贴板数据

$(document).on('paste', '#pasteIt', function(e) { 
 
    e.preventDefault(); 
 
    // prevent copying action 
 
    alert(e.originalEvent.clipboardData.getData('Text')); 
 
    var withoutSpaces = e.originalEvent.clipboardData.getData('Text'); 
 
    withoutSpaces = withoutSpaces.replace(/\s+/g, ''); 
 
    $(this).val(withoutSpaces); 
 
    // you need to use val() not text() 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="text" id="pasteIt" placeholder="Paste something here">

编号:https://forum.jquery.com/topic/paste-event-get-the-value-of-the-paste#14737000004101955

+0

它的工作原理!你能解释一下什么'e.preventDefault(); alert(e.originalEvent.clipboardData.getData('Text'));'do?谢谢! – Dave

+0

'e.preventDefault(); '是为了避免默认操作,即将内容复制到输入框。我们不需要执行,而是我们需要粘贴删除空格的值 –

+0

'e.originalEvent.clipboardData.getData('Text')'用于获取剪贴板内容 –

2

使用setTimeout,这会延迟检查以便检索值。 看看吧here

$(document).on('paste', '#pasteIt', function() { 
    setTimeout(function() { 
     alert($("#pasteIt").val()); 
     var withoutSpaces = $("#pasteIt").val(); 
     withoutSpaces = withoutSpaces.replace(/\s+/g, ''); 
     $("#pasteIt").val(withoutSpaces); 
    }, 1); 
}); 
+0

这不是工作.. – Dave

+0

它的确如此,但Pranav的解决方案是一个更好的解决方案。尝试一下。 – TheOnlyError

+0

您必须使用'.val',而不是'.text'来设置值 –

0

所以,你要这样:

$(document).on('paste', '#pasteIt', function(e) { 
 
    window.setTimeout(function() { 
 
    var withoutSpaces = $("#pasteIt").val(); 
 
    withoutSpaces = withoutSpaces.replace(/\s+/g, ''); 
 
    $("#pasteIt").val(withoutSpaces); 
 
    }, 1); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<html> 
 
<span>Enter: </span> 
 
<input id="pasteIt"> 
 

 
</html>