your programing

jQuery에서 이벤트 핸들러를 제거하는 가장 좋은 방법은 무엇입니까?

lovepro 2020. 9. 27. 13:36
반응형

jQuery에서 이벤트 핸들러를 제거하는 가장 좋은 방법은 무엇입니까?


나는 input type="image". 이것은 Microsoft Excel의 셀 노트처럼 작동합니다. 누군가 이것이 input-image쌍을 이루는 텍스트 상자에 숫자를 입력 하면 input-image. 그런 다음 사용자가를 클릭 image하면 데이터에 메모를 추가 할 수있는 작은 팝업이 표시됩니다.

내 문제는 사용자가 텍스트 상자에 0을 입력하면 input-image의 이벤트 처리기 를 비활성화해야한다는 것 입니다. 다음을 시도했지만 아무 소용이 없습니다.

$('#myimage').click(function { return false; });

jQuery ≥ 1.7

jQuery 1.7 이상에서는 이벤트 API가 업데이트되었으며 .bind()/ .unbind()는 이전 버전과의 호환성을 위해 계속 사용할 수 있지만 선호되는 방법은 on () / off () 함수를 사용하는 것입니다. 이제 아래는,

$('#myimage').click(function() { return false; }); // Adds another click event
$('#myimage').off('click');
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');

jQuery <1.7

예제 코드에서는 이전 클릭 이벤트를 재정의하지 않고 단순히 이미지에 다른 클릭 이벤트를 추가하는 것입니다.

$('#myimage').click(function() { return false; }); // Adds another click event

그러면 두 클릭 이벤트가 모두 시작됩니다.

사람들이 말했듯이 unbind를 사용하여 모든 클릭 이벤트를 제거 할 수 있습니다.

$('#myimage').unbind('click');

단일 이벤트를 추가 한 다음 제거하려면 (추가되었을 수있는 다른 이벤트를 제거하지 않고) 이벤트 네임 스페이스를 사용할 수 있습니다.

$('#myimage').bind('click.mynamespace', function() { /* Do stuff */ });

이벤트 만 제거하려면 :

$('#myimage').unbind('click.mynamespace');

이 질문에 대한 답변을 받았을 때는 사용할 수 없었지만 live () 메서드를 사용하여 이벤트를 활성화 / 비활성화 할 수도 있습니다 .

$('#myimage:not(.disabled)').live('click', myclickevent);

$('#mydisablebutton').click( function () { $('#myimage').addClass('disabled'); });

이 코드를 사용하면 #mydisablebutton을 클릭하면 비활성화 된 클래스가 #myimage 요소에 추가됩니다. 이렇게하면 선택기가 더 이상 요소와 일치하지 않으며 'disabled'클래스가 제거되어 .live () 선택기가 다시 유효하게 될 때까지 이벤트가 발생하지 않습니다.

이 클래스를 기반으로 스타일을 추가하면 다른 이점도 있습니다.


바인딩 해제 기능을 사용하면됩니다.

$('#myimage').unbind('click');

jquery의 동일한 객체 및 이벤트에 여러 이벤트 핸들러를 추가 할 수 있습니다. 이것은 새로운 것을 추가하는 것이 이전 것을 대체하지 않는다는 것을 의미합니다.

이벤트 네임 스페이스와 같은 이벤트 처리기를 변경하기위한 몇 가지 전략이 있습니다. 온라인 문서에는 이에 대한 몇 가지 페이지가 있습니다.

이 질문을보세요 (바인딩 해제에 대해 배웠던 방법입니다). 답변에 이러한 전략에 대한 유용한 설명이 있습니다.

jquery에서 바인딩 된 호버 콜백 함수를 읽는 방법


이벤트 에 한 번만 응답하려는 경우 다음 구문이 매우 유용합니다.

 $('.myLink').bind('click', function() {
   //do some things

   $(this).unbind('click', arguments.callee); //unbind *just this handler*
 });

arguments.callee를 사용 하면 하나의 특정 익명 함수 핸들러가 제거되어 주어진 이벤트에 대해 단일 시간 핸들러가 있는지 확인할 수 있습니다. 이것이 다른 사람들에게 도움이되기를 바랍니다.


아마도 unbind 방법이 당신을 위해 일할 것입니다.

$("#myimage").unbind("click");

prop 및 attr을 사용하여 이벤트를 null로 설정해야했습니다. 나는 둘 중 하나와 그것을 할 수 없었다. 또한 .unbind를 작동시킬 수 없었습니다. TD 요소를 작업 중입니다.

.prop("onclick", null).attr("onclick", null)

이벤트 가이 방법으로 연결 되고 대상이 연결 해제되는 경우 :

$('#container').on('click','span',function(eo){
    alert(1);

    $(this).off(); //seams easy, but does not work

    $('#container').off('click','span'); //clears click event for every span

    $(this).on("click",function(){return false;}); //this works.

});​

onclick핸들러를 인라인 마크 업 으로 추가 할 수 있습니다 .

<input id="addreport" type="button" value="Add New Report" onclick="openAdd()" />

그렇다면 jquery .off()또는 .unbind()작동하지 않습니다. jquery에서도 원래 이벤트 핸들러를 추가해야합니다.

$("#addreport").on("click", "", function (e) {
   openAdd();
});

그런 다음 jquery는 이벤트 핸들러에 대한 참조를 가지며이를 제거 할 수 있습니다.

$("#addreport").off("click")

VoidKing mentions this a little more obliquely in a comment above.


Updated for 2014

Using the latest version of jQuery, you're now able to unbind all events on a namespace by simply doing $( "#foo" ).off( ".myNamespace" );


Thanks for the information. very helpful i used it for locking page interaction while in edit mode by another user. I used it in conjunction with ajaxComplete. Not necesarily the same behavior but somewhat similar.

function userPageLock(){
    $("body").bind("ajaxComplete.lockpage", function(){
        $("body").unbind("ajaxComplete.lockpage");
        executePageLock();      
    });
};  

function executePageLock(){
    //do something
}

Best way to remove inline onclick event is $(element).prop('onclick', null);


In case .on() method was previously used with particular selector, like in the following example:

$('body').on('click', '.dynamicTarget', function () {
    // Code goes here
});

Both unbind() and .off() methods are not going to work.

However, .undelegate() method could be used to completely remove handler from the event for all elements which match the current selector:

$("body").undelegate(".dynamicTarget", "click")

To remove ALL event-handlers, this is what worked for me:

To remove all event handlers mean to have the plain HTML structure without all the event handlers attached to the element and its child nodes. To do this, jQuery's clone() helped.

var original, clone;
// element with id my-div and its child nodes have some event-handlers
original = $('#my-div');
clone = original.clone();
//
original.replaceWith(clone);

With this, we'll have the clone in place of the original with no event-handlers on it.

Good Luck...


This also works fine .Simple and easy.see http://jsfiddle.net/uZc8w/570/

$('#myimage').removeAttr("click");

If you use $(document).on() to add a listener to a dynamically created element then you may have to use the following to remove it:

// add the listener
$(document).on('click','.element',function(){
    // stuff
});

// remove the listener
$(document).off("click", ".element");


if you set the onclick via html you need to removeAttr ($(this).removeAttr('onclick'))

if you set it via jquery (as the after the first click in my examples above) then you need to unbind($(this).unbind('click'))


I know this comes in late, but why not use plain JS to remove the event?

var myElement = document.getElementByID("your_ID");
myElement.onclick = null;

or, if you use a named function as an event handler:

function eh(event){...}
var myElement = document.getElementByID("your_ID");
myElement.addEventListener("click",eh); // add event handler
myElement.removeEventListener("click",eh); //remove it

All the approaches described did not work for me because I was adding the click event with on() to the document where the element was created at run-time:

$(document).on("click", ".button", function() {
    doSomething();
});


My workaround:

As I could not unbind the ".button" class I just assigned another class to the button that had the same CSS styles. By doing so the live/on-event-handler ignored the click finally:

// prevent another click on the button by assigning another class
$(".button").attr("class","buttonOff");

Hope that helps.


Hope my below code explains all. HTML:

(function($){

     $("#btn_add").on("click",function(){
       $("#btn_click").on("click",added_handler);
       alert("Added new handler to button 1");
     });

  
 
     $("#btn_remove").on("click",function(){
       $("#btn_click").off("click",added_handler);
       alert("Removed new handler to button 1");
     });

  
   function fixed_handler(){
    alert("Fixed handler");
  }
  
   function added_handler(){
    alert("new handler");
  }
  
  $("#btn_click").on("click",fixed_handler);
  $("#btn_fixed").on("click",fixed_handler);
  
  
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_click">Button 1</button>
  <button id="btn_add">Add Handler</button>
  <button id="btn_remove">Remove Handler</button>
  <button id="btn_fixed">Fixed Handler</button>

참고URL : https://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery

반응형