2010-02-11 90 views
13

我必须使用JQuery来获取文本区域的粘贴事件。我曾尝试下面的代码,但它是不工作...使用JQuery捕获粘贴到textarea中的文本

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

回答

21

你可以做这样的事情

$("#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); 
}); 
+0

如果您按Ctrl + V进行粘贴,则此方法可用。但如果您右键单击鼠标并选择“粘贴”,则不起作用。 – JohnnyLinTW 2013-06-26 06:33:01

+6

我发现如果改为$(“#txtcomplaint”)。bind('paste',null,function(e)...并且它对Ctrl + V和鼠标粘贴工作正常。 – JohnnyLinTW 2013-06-26 08:01:16

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

有关其他资源看一看here

+0

您将不会使用此方法获取复制的文本。 – rahul 2010-02-11 05:29:37

+0

@rahul:他只想用这个事件来计算海豚的文字。 – 2010-02-11 05:33:50

1

我终于拿到了这1)输入,2)拖放,3)按Ctrl-V工作,4)从鼠标的右键菜单粘贴点击,但我不得不附上膏体拖放处理程序文件(其中“taValue”是类我试图监视文字区域的):

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

上textarea的KeyUp事件已经奏效。接下来的问题是paste和drop事件在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] 

我讨厌使用超时这样的事情,但它的工作(当我试图100ms的时间间隔,它没有)。

0

这是最有用的解决方案:

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

也许改变不是必需的。