program story

jQuery의 이벤트 핸들러에 인수를 어떻게 전달할 수 있습니까?

inputbox 2020. 9. 7. 08:04
반응형

jQuery의 이벤트 핸들러에 인수를 어떻게 전달할 수 있습니까?


다음과 같은 jQuery 코드를 사용합니다.

$("#myid").click(myfunction);

function myfunction(arg1, arg2) {/* something */}

myfunctionjQuery를 사용 하는 동안 인수를 어떻게 전달 합니까?


가장 간단한 방법은 이렇게하는 것입니다 (이벤트 정보가 함수에 전달되는 것을 원하지 않는다고 가정) ...

$("#myid").click(function() {
    myfunction(arg1, arg2);
});

jsFiddle .

그러면 click이벤트가 트리거 될 때 호출되는 익명 함수가 생성됩니다 . 이것은 차례로 myfunction()당신이 제공하는 인수 로 호출 됩니다.

당신은 유지하려는 경우 ThisBinding(값 this이벤트를 트리거 요소로 설정 함수가 호출 될 때를) 다음과 함께 함수를 호출합니다 call().

$("#myid").click(function() {
    myfunction.call(this, arg1, arg2);
});

jsFiddle .

예제에서 설명한 방식으로 참조를 직접 전달할 수 없으며 단일 인수가 jQuery event객체가 됩니다.

당신이 경우 않는 참조를 전달하려면, 당신은 jQuery의 활용해야한다 proxy()(크로스 브라우저 랩퍼 인 기능 Function.prototype.bind()). 이것은 당신이 바인딩 인수를 전달할 수 있습니다 전에event 인수입니다.

$("#myid").click($.proxy(myfunction, null, arg1, arg2));   

jsFiddle .

이 예에서, myfunction()함께 실행됩니다의 ThisBinding손상 ( null하지 객체, 그래서 정상적인 this이벤트가 사용되는 트리거 요소의 값) 인수 (순서대로)와 함께, arg1, arg2그리고 마지막의 jQuery event당신이 무시할 수 개체, 필요하지 않은 경우 (함수 인수에 이름을 지정하지 마십시오).

jQuery event객체를 사용하여 data데이터를 전달할 수도 있지만 ( 질문에 언급 된 것과 같은 함수 인수 가 아님)을 myfunction()통해 액세스 하도록 수정 하거나 적어도 이전 예제 또는 생성 된 것과 같은 수동 프록시 기능을 도입해야합니다. 후자의 예를 사용합니다.event.data.arg1


$("#myid").on('click', {arg1: 'hello', arg2: 'bye'}, myfunction);

function myfunction(e) {

    var arg1 = e.data.arg1;
    var arg2 = e.data.arg2;

    alert(arg1);
    alert(arg2);

}

//call method directly:
myfunction({
    arg1: 'hello agian', 
    arg2: 'bye again'
});

또한 on 및 off 메서드를 사용하여 특정 이벤트 처리기를 바인딩 및 바인딩 해제 할 수 있습니다.

예:

$("#myid").off('click', myfunction);

이것은 #myid에서 myfunction 핸들러의 바인딩을 해제합니다.


Alex의 대답을 반드시 사용해야하지만 프로토 타입 라이브러리의 "bind"메서드는 Ecmascript 5에서 표준화되었으며 곧 브라우저에서 기본적으로 구현 될 것입니다. 다음과 같이 작동합니다.

jQuery("#myid").click(myfunction.bind(this, arg1, arg2));

이전 스레드이지만 검색 용입니다. 시험:

$(selector).on('mouseover',...);

... and check out the "data" parameter: http://api.jquery.com/on/

e.g.:

function greet( event ) {
  alert( "Hello " + event.data.name );
}
$( "button" ).on( "click", {name: "Karl"}, greet );
$( "button" ).on( "click", {name: "Addy"}, greet );

There are great answers already, but anyway, here are my two cents. You can also use:

$("#myid").click({arg1: "foo", arg2: "bar"}, myfunction)

And the listener would look like:

function myfunction(event){ alert(event.data.arg1); alert(event.data.arg2); }


Simple:

$(element).on("click", ["Jesikka"],  myHandler);

function myHandler(event){
   alert(event.data);     //passed in "event.data"
}

참고URL : https://stackoverflow.com/questions/979337/how-can-i-pass-arguments-to-event-handlers-in-jquery

반응형