如何在jquery中获取最终粘贴的文本?

How to get the final pasted text in jquery?

我想 trim 当用户在其上书写或粘贴文本时在字段中添加文本,以下代码效果很好但只有一个问题,即当用户选择所有文本来替换它时用粘贴的文本或把光标插入粘贴的文本里面,代码在最后重复当前值+新值,如何解决?

$(document).on('paste', "input[type='text'], textarea", function(e) {

            let val = $(this).val();            
            val = val.trim();
            val = val.replace(/(?:^\s+|\s+?(\s))(\S+)/g, "");
              val = val.replace(/\s+(\s)$/, "");
            $(this).val( val );

    } );

我相信我需要做的是正常粘贴,获取最终粘贴的文本并trim它,但这就是问题How to get the final pasted text?你能帮忙吗?

问题是您的 trim 代码首先是 运行(导致将数据的一个副本放置在元素中),然后粘贴发生(导致数据的第二个副本在末尾)。

If we delay the trim code, the issue is resolved very simply:

$("#txtInput, textarea").on('paste', function(e) {
  // Store the invocation context (the input element) 
  // because it will change in the setTimeout
  var ctx = this;

  // Wait 1/10th of a second before trimming the data
  // This will allow the paste to complete normally.
  setTimeout(function(){
     $(ctx).val($(ctx).val().trim());            
  }, 100);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtInput" size="40" value="  there are leading and trailing spaces here   ">
<textarea></textarea>

简而言之,粘贴事件不是允许您即时更改粘贴文本的管道。您可以访问剪贴板,但从中获取数据有点困难,因为 questionable browser support 不仅针对粘贴事件,而且针对所述事件中的剪贴板数据。

onChange 或 onBlur 是您的最佳选择,因为这是更新您的值的好时机,即使在用户粘贴他们的值之后也是如此:

$("input[type='text'], textarea").bind('blur', function(e) {
        $(this).val($.trim($(this).val()));
} );

无论是输入空格还是粘贴空格,这都行得通。如果必须粘贴,那么您可能希望使用上面的内容和粘贴事件,但粘贴事件仅设置shared boolean like "valueIsPasted" 为 true,然后只有当该值为 true 时才能执行上述操作。我不喜欢那个解决方案,但不幸的是,粘贴支持不是很好。最重要的是,这在不支持粘贴事件的IE中仍然不起作用。

更新:

看起来像 W3Schools begs to differ on browser support; however, I still feel that onChange or onBlur are your best bets as it will allow you to change the value once the user is done editing the value or done with the control, and definitely work. Check out my codepen