jQuery enlazar a Pegar Evento, cómo obtener el contenido de la pasta


Tengo un complemento jquery token tagit y quiero unirme al evento pegar para agregar elementos correctamente.

Soy capaz de enlazar al evento de pegado de la siguiente manera:

    .bind("paste", paste_input)

...

function paste_input(e) {
    console.log(e)
    return false;
}

¿Cómo puedo obtener el valor real del contenido pegado?

Author: Benjamin, 2012-07-23

8 answers

Hay un evento onpaste que funciona en los navegadores modernos. Puede acceder a los datos pegados utilizando la función getData en el objeto clipboardData.

$("#textareaid").bind("paste", function(e){
    // access the clipboard using the api
    var pastedData = e.originalEvent.clipboardData.getData('text');
    alert(pastedData);
} );

Tenga en cuenta que bindy unbind están obsoletos a partir de jQuery 3. La llamada preferida es en.

Todos los navegadores modernos soportan la API del portapapeles .

Ver también: En Jquery ¿Cómo manejar la pasta?

 93
Author: jeff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-25 18:11:36

¿qué tal esto: http://jsfiddle.net/5bNx4/

Utilice .on si está utilizando jq1.7 et al.

Comportamiento: Cuando escribe cualquier cosa o paste cualquier cosa en el 1er textarea, la teaxtarea a continuación captura el cahnge.

Descanso Espero que ayude a la causa. :)

Enlace útil = >

¿Cómo se maneja oncut, oncopy y onpaste en jQuery?

Entrada de pasta de captura

Código

$(document).ready(function() {
    var $editor    = $('#editor');
    var $clipboard = $('<textarea />').insertAfter($editor);

    if(!document.execCommand('StyleWithCSS', false, false)) {
        document.execCommand('UseCSS', false, true);
    }

    $editor.on('paste, keydown', function() {
        var $self = $(this);            
        setTimeout(function(){ 
            var $content = $self.html();             
            $clipboard.val($content);
        },100);
     });
});
 17
Author: Tats_innit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:36

Recientemente necesitaba lograr algo similar a esto. Utilicé el siguiente diseño para acceder al elemento pegar y al valor. jsFiddle demo

$('body').on('paste', 'input, textarea', function (e)
{
    setTimeout(function ()
    {
        //currentTarget added in jQuery 1.3
        alert($(e.currentTarget).val());
        //do stuff
    },0);
});
 6
Author: Kevin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-24 18:08:28

Puede comparar el valor original del campo y el valor cambiado del campo y deducir la diferencia como el valor pegado. Esto captura el texto pegado correctamente incluso si hay texto existente en el campo.

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);
    });
});
 1
Author: Alo Sarv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-06 18:23:55
$(document).ready(function() {
    $("#editor").bind('paste', function (e){
        $(e.target).keyup(getInput);
    });

    function getInput(e){
        var inputText = $(e.target).html(); /*$(e.target).val();*/
        alert(inputText);
        $(e.target).unbind('keyup');
    }
});
 1
Author: Cyrus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-04 07:43:49

Parecería que este evento tiene alguna propiedad clipboardData adjunta (puede estar anidado dentro de la propiedad originalEvent). El clipboardData contiene una matriz de elementos y cada uno de esos elementos tiene una función getAsString() que puede llamar. Esto devuelve la representación de cadena de lo que está en el elemento.

Esos elementos también tienen una función getAsFile(), así como algunos otros que son específicos del navegador (por ejemplo, en los navegadores webkit, hay una función webkitGetAsEntry()).

Para mis propósitos, necesitaba el valor de cadena de lo que se está pegando. Entonces, hice algo similar a esto:

$(element).bind("paste", function (e) {
    e.originalEvent.clipboardData.items[0].getAsString(function (pStringRepresentation) {
        debugger; 
        // pStringRepresentation now contains the string representation of what was pasted.
        // This does not include HTML or any markup. Essentially jQuery's $(element).text()
        // function result.
    });
});

Querrá realizar una iteración a través de los elementos, manteniendo un resultado de concatenación de cadena.

El hecho de que haya una matriz de elementos me hace pensar que se necesitará hacer más trabajo, analizando cada elemento. También querrá hacer algunas comprobaciones null / value.

 1
Author: Chandler Zwolle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-23 15:17:13

Esto funciona en todo el navegador para obtener el valor pegado. Y también para crear un método común para todos los cuadros de texto.

$("#textareaid").bind("paste", function(e){       
    var pastedData = e.target.value;
    alert(pastedData);
} )
 1
Author: Mukesh Kalgude,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-30 05:09:45

Otro enfoque: Ese evento input atrapará también el evento paste.

$('textarea').bind('input', function () {
    setTimeout(function () { 
        console.log('input event handled including paste event');
    }, 0);
});
 0
Author: Shahar Shukrani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-25 11:33:48