jQuery bind to Paste Event, how to get the content of the paste

后端 未结 9 1080
温柔的废话
温柔的废话 2020-11-28 06:08

I have a jquery token tagit plugin and I want to bind to the paste event to add items correctly.

I\'m able to bind to the paste event like so:

    .b         


        
9条回答
  •  一个人的身影
    2020-11-28 06:51

    You could compare the original value of the field and the changed value of the field and deduct the difference as the pasted value. This catches the pasted text correctly even if there is existing text in the field.

    http://jsfiddle.net/6b7sK/

    function text_diff(first, second) {
        var start = 0;
        while (start < first.length && first[start] == second[start]) {
            ++start;
        }
        var end = 0;
        while (first.length - end > start && first[first.length - end - 1] == second[second.length - end - 1]) {
            ++end;
        }
        end = second.length - end;
        return second.substr(start, end - start);
    }
    $('textarea').bind('paste', function () {
        var self = $(this);
        var orig = self.val();
        setTimeout(function () {
            var pasted = text_diff(orig, $(self).val());
            console.log(pasted);
        });
    });
    

提交回复
热议问题