使用 JQuery 捕获粘贴到 textarea 中的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2242442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:05:38  来源:igfitidea点击:

Capture text pasted into a textarea with JQuery

jquerycopy-pastejquery-events

提问by Jibu P C_Adoor

I have to take the paste event of a text area using JQuery. I have tried the following code but it is not working...

我必须使用 JQuery 来获取文本区域的粘贴事件。我已经尝试了以下代码,但它不起作用...

$(document).ready(function()
{ 
  $('#txtcomplaint').keyup(function()
  {  
     TextCounter('txtcomplaint','counterComplaint', 1000 ); 
  }) 
  $('#txtcomplaint').onpaste(function()
  {  
     alert()
     //TextCounter('txtcomplaint','counterComplaint', 1000 ); 
  }) 
});

回答by rahul

You can do something like this

你可以做这样的事情

$("#txtcomplaint").bind('paste', function(e) {
    var elem = $(this);

    setTimeout(function() {
        // gets the copied text after a specified time (100 milliseconds)
        var text = elem.val(); 
    }, 100);
});

回答by Fitzchak Yitzchaki

$('#txtcomplaint').bind('paste', function(e){ alert('pasting!') });
$('#txtcomplaint').bind('paste', function(e){ alert('pasting!') });

For additional resource take a look here.

有关其他资源,请查看此处

回答by Gullbyrd

I finally got this to work for 1) typing, 2) drag and drop, 3) Ctrl-V and 4) paste from the context menu of a mouse click, but I had to attach the paste and drop handlers to the document (where 'taValue' is the class of the textareas I'm trying to monitor):

我终于让它可以用于 1) 打字,2) 拖放,3) Ctrl-V 和 4) 从单击鼠标的上下文菜单中粘贴,但我必须将粘贴和拖放处理程序附加到文档(其中'taValue' 是我试图监控的 textareas 的类):

        $(document).on("paste drop", '.taValue', function (e) {
          myHandler.call(e.target, e);
        });

The keyup event on the textarea already worked. The next problem was that the paste and drop events get fired BEFORE the text in the textarea actually changes. In my case I wanted to compare the new text to the original text. I resorted to a setTimeout:

textarea 上的 keyup 事件已经起作用。下一个问题是在 textarea 中的文本实际更改之前,粘贴和放置事件会被触发。就我而言,我想将新文本与原始文本进行比较。我求助于setTimeout:

    function myHandler(e) {
      if (e && (e.type === "drop" || e.type === "paste")) {
        var me = this;
        setTimeout(function () { myHandler.call(me) }, 200);
      }... [more code to do the comparison]

I hate using timeouts for things like this but it does work (when I tried a 100ms interval, it did not).

我讨厌对这样的事情使用超时,但它确实有效(当我尝试 100 毫秒的间隔时,它没有)。

回答by hatanooh

This is the most useful solution:

这是最有用的解决方案:

$("#item_name").bind("input change", function() {});

maybe change is not essential.

也许改变不是必需的。