Why Paste Event in jquery fires on pre-paste?

孤街醉人 提交于 2019-12-10 14:30:04

问题


I am trying to make textbox similar to the Twitter, for this i have written code for

  • Word Count
  • Used Events Change, Keyup and Paste

Keyup and Change Events are working fine but paste event is little bit strange, when i paste something in textarea the word count doesn't change at that moment, after some debugging i found that paste event fires up before pasting something on textbox. I don't know how they handle this in Twitter. Here is my code : events:

'click #textboxId'  : 'submitQuestion'
'keyup #textboxId'  : 'wordCounter'
'change #textboxId' : 'wordCounter'
'paste #textboxId'  : 'wordCounter'

wordCounter: ->  
  #Code for Word Count#  

Due to pre-paste nature of paste event the work count doesn't changes on that instance.
Your suggestion and help will be appreciated, Thanks for your time.


回答1:


See this example.

http://jsfiddle.net/urEhK/1

$('textarea').bind('input propertychange', function() {
    $('#output').html($(this).val().length + ' characters');
});

That behavior was very weird. You would think that one of those events would catch this properly? I was surprised there weren't more answers to this via Google.




回答2:


   function update()    
   {
       alert($textbox.val().length);
   }


    var $textbox = $('input');
    $textbox.bind('keyup change cut paste', function(){
        update(); //code to count or do something else
    });
    // And this line is to catch the browser paste event
    $textbox.bind('input paste',function(e){ setTimeout( update, 250); });  



回答3:


You should now use on() instead of bind() see this post. It's also unnecessary to create a named function, you can just create a anonymous function.

$('#pasteElement').on('paste', function() {
    setTimeout(function(){
        alert($('#pasteElement').val());
    }, 100);
});



回答4:


You can do one thing that firstly get original data . then you can get the event paste data and add them.

  $("#id").on("paste keypress ",function(event){
                // eg. you want to get last lenght
                 var length=$("#id").val().length;
                 if(event.type == "paste"){
                    //then you can get paste event data.=

length+=event.originalEvent.clipboardData.getData('text').length;
                }


            });`


来源:https://stackoverflow.com/questions/8557995/why-paste-event-in-jquery-fires-on-pre-paste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!