programing

jQuery bind to Paste Event, 붙여넣기 내용을 가져오는 방법

easyjava 2023. 9. 6. 23:07
반응형

jQuery bind to Paste Event, 붙여넣기 내용을 가져오는 방법

jquery token tagit 플러그인이 있는데 아이템을 올바르게 추가하기 위해 붙여넣기 이벤트에 바인딩하고 싶습니다.

다음과 같이 붙여넣기 이벤트에 바인딩할 수 있습니다.

    .bind("paste", paste_input)

...

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

실제 붙여넣기한 내용 값을 얻으려면 어떻게 해야 합니까?

현대 브라우저에서 작동하는 붙여넣기 이벤트가 있습니다.다음을 사용하여 붙여넣은 데이터에 액세스할 수 있습니다.getData의 기능을 다함clipboardData물건.

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

bind와 unbind는 jQuery 3에서 더 이상 사용되지 않습니다.우선 통화는 켜는 것입니다.

모든 현대 브라우저는 클립보드 API를 지원합니다.

참고 항목:쥬리에서 페이스트 처리하는 법?

이것은 어떻습니까? http://jsfiddle.net/5bNx4/

사용해주세요.on만약 당신이 jq1.7 등을 사용하고 있습니다.

동작:뭐든지 입력할 때나paste첫번째 텍스트 영역에 있는 모든 것 아래의 텍스트 영역은 변경 내용을 캡처합니다.

휴식 나는 그것이 대의에 도움이 되기를 바랍니다.:)

도움이 되는 링크 =>

jQuery에서 컷, 복사, 붙여넣기를 어떻게 처리합니까?

붙여넣기 입력 잡기

편집:
이벤트 목록 내.on()공백으로 구분해야 합니다.https://api.jquery.com/on/ 참조

코드를

$(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);
     });
});

저는 최근에 이와 비슷한 일을 해내야 했습니다.paste 요소와 value에 접근하기 위해 다음과 같은 디자인을 사용했습니다. jsFiddle dem

$('body').on('paste', 'input, textarea', function (e)
{
    setTimeout(function ()
    {
        //currentTarget added in jQuery 1.3
        alert($(e.currentTarget).val());
        //do stuff
    },0);
});

또 다른 접근 방식:그거input이벤트는 또한 잡을 것입니다.paste이벤트성의

$('textarea').bind('input', function () {
    setTimeout(function () { 
        console.log('input event handled including paste event');
    }, 0);
});

현대 브라우저에서는 inputType 속성과 함께 입력 이벤트를 사용하기만 하면 됩니다.

$(document).on('input', 'input, textarea', function(e){
  if (e.originalEvent.inputType == 'insertFromPaste') {
    alert($(this).val());
  }
});

https://codepen.io/anon/pen/jJOWxg

$(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');
    }
});

붙여넣기된 값을 얻으려면 모든 브라우저에서 작동합니다.또한 모든 텍스트 상자에 대해 공통 메서드를 만듭니다.

$("#textareaid").bind("paste", function(e){       
    var pastedData = e.target.value;
    alert(pastedData);
} )

필드의 원래 값과 필드의 변경된 값을 비교하여 그 차이를 붙여넣은 값으로 공제할 수 있습니다.필드에 기존 텍스트가 있더라도 붙여넣은 텍스트를 올바르게 가져옵니다.

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);
    });
});

마치 이 사건이 몇 가지를 가지고 있는 것처럼 보일 것입니다.clipboardData연결된 속성(내에 중첩될 수 있음)originalEvent재산).clipboardData항목의 배열을 포함하고 각 항목은getAsString()호출할 수 있는 함수입니다.항목에 있는 내용의 문자열 표현을 반환합니다.

그 물건들은 또한.getAsFile()함수 뿐만 아니라 브라우저에 특정한 일부 다른 것들(예를 들어 웹킷 브라우저에는webkitGetAsEntry()함수).

제 목적을 위해서는 붙여넣기 하는 것의 문자열 값이 필요했습니다.그래서 저는 이와 비슷한 일을 했습니다.

$(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.
    });
});

문자열 연결 결과를 유지하면서 항목을 반복 수행할 수 있습니다.

여러 항목이 있다는 사실은 각 항목을 분석하면서 더 많은 작업이 필요할 것으로 생각하게 합니다.또한 null/value 검사를 수행해야 합니다.

나는 그렇게 합니다. 이것은 인간이 사용하는 대부분의 브라우저에서 작동합니다.

$("#couponCode").bind("change keyup input paste",function () {
   const value=  document.getElementById("couponCode").value;
});

언급URL : https://stackoverflow.com/questions/11605415/jquery-bind-to-paste-event-how-to-get-the-content-of-the-paste

반응형