programing tip

jQuery를 사용하여 event.preventDefault ()를 호출하는 리스너를 바인딩 해제하는 방법은 무엇입니까?

itbloger 2020. 7. 5. 08:11
반응형

jQuery를 사용하여 event.preventDefault ()를 호출하는 리스너를 바인딩 해제하는 방법은 무엇입니까?


jquery 토글은 기본적으로 preventDefault ()를 호출하므로 기본값이 작동하지 않습니다. 확인란을 클릭하거나 링크 등을 클릭 할 수 없습니다.

기본 핸들러를 복원 할 수 있습니까?


나의 경우에는:

$('#some_link').click(function(event){
    event.preventDefault();
});

$('#some_link').unbind('click'); 기본 작업을 복원하는 유일한 방법으로 작동했습니다.

여기에서 볼 수 있듯이 : https://stackoverflow.com/a/1673570/211514


상당히 간단합니다

당신이 같은 것을한다고 가정 해 봅시다.

document.ontouchmove = function(e){ e.preventDefault(); }

이제 원래 상황으로 되돌리려면 다음을 수행하십시오.

document.ontouchmove = function(e){ return true; }

웹 사이트에서 .


복원 preventDefault()할 수는 없지만 할 수있는 일은 속임수입니다. :)

<div id="t1">Toggle</div>
<script type="javascript">
$('#t1').click(function (e){
   if($(this).hasClass('prevented')){
       e.preventDefault();
       $(this).removeClass('prevented');
   }else{
       $(this).addClass('prevented');
   }
});
</script>

한 단계 더 나아가려면 트리거 버튼을 사용하여 이벤트를 트리거 할 수도 있습니다.


function DoPrevent(e) {
  e.preventDefault();
  e.stopPropagation();
}

// Bind:
$(element).on('click', DoPrevent);

// UnBind:
$(element).off('click', DoPrevent);

경우에 따라 * return false대신에 대신에 e.preventDefault()기본값을으로 복원 할 수 있습니다 return true.

* 이벤트 버블 링을 신경 쓰지 않고 e.stopPropagation()함께 사용하지 않을 때의 의미e.preventDefault()

유사한 질문 도 참조하십시오 (스택 오버플로에도 있음)

또는 확인란의 경우 다음과 같은 것을 가질 수 있습니다.

$(element).toggle(function(){
  $(":checkbox").attr('disabled', true);
  },
function(){
   $(":checkbox").removeAttr('disabled');
}) 

다음을 수행하여 기본 조치 (HREF 추적 인 경우)를 복원 할 수 있습니다.

window.location = $(this).attr('href');


이 코드를 테스트하면 문제가 해결되는 것 같습니다.

event.stopPropagation();

참고


네임 스페이스를 사용하여이를 수행하는 가장 좋은 방법입니다. 안전하고 안전한 방법입니다. 여기에서 .rb는 바인딩 해제 기능이 특정 키 다운에서 작동하지만 다른 키 다운에서는 작동하지 않도록하는 네임 스페이스입니다.

$(document).bind('keydown.rb','Ctrl+r',function(e){
            e.stopImmediatePropagation();
            return false;
        });

$(document).unbind('keydown.rb');

심판 1 : http://idodev.co.uk/2014/01/safely-binding-to-events-using-namespaces-in-jquery/

ref2: http://jqfundamentals.com/chapter/events


if it is a link then $(this).unbind("click"); would re-enable the link clicking and the default behavior would be restored.

I have created a demo JS fiddle to demonstrate how this works:

Here is the code of the JS fiddle:

HTML:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<a href="http://jquery.com">Default click action is prevented, only on the third click it would be enabled</a>
<div id="log"></div>

Javascript:

<script>
var counter = 1;
$(document).ready(function(){
$( "a" ).click(function( event ) {
  event.preventDefault();

  $( "<div>" )
    .append( "default " + event.type + " prevented "+counter )
    .appendTo( "#log" );

    if(counter == 2)
    {
        $( "<div>" )
    .append( "now enable click" )
    .appendTo( "#log" );

    $(this).unbind("click");//-----this code unbinds the e.preventDefault() and restores the link clicking behavior
    }
    else
    {
        $( "<div>" )
    .append( "still disabled" )
    .appendTo( "#log" );
    }
    counter++;
});
});
</script>

Disable:

document.ontouchstart = function(e){ e.preventDefault(); }

Enable:

document.ontouchstart = function(e){ return true; }

I had a problem where I needed the default action only after some custom action (enable otherwise disabled input fields on a form) had concluded. I wrapped the default action (submit()) into an own, recursive function (dosubmit()).

var prevdef=true;
var dosubmit=function(){
    if(prevdef==true){
        //here we can do something else first//
        prevdef=false;
        dosubmit();
    }
    else{
        $(this).submit();//which was the default action
    }
};

$('input#somebutton').click(function(){dosubmit()});

Use a boolean:

let prevent_touch = true;
document.documentElement.addEventListener('touchmove', touchMove, false);
function touchMove(event) { 
    if (prevent_touch) event.preventDefault(); 
}

I use this in a Progressive Web App to prevent scrolling/zooming on some 'pages' while allowing on others.


You can set to form 2 classes. After you set your JS script to one of them, when you want to disable your script, you just delete the class with binded script from this form.

HTML:

<form class="form-create-container form-create"> </form>   

JS

$(document).on('submit', '.form-create', function(){ 
..... ..... ..... 
$('.form-create-container').removeClass('form-create').submit();

});

$('#my_elementtt').click(function(event){
    trigger('click');
});

I'm not sure you're what you mean: but here's a solution for a similar (and possibly the same) problem...

I often use preventDefault() to intercept items. However: it's not the only method of interception... often you may just want a "question" following which behaviour continues as before, or stops. In a recent case I used the following solution:

$("#content").on('click', '#replace', (function(event){ return confirm('Are you sure you want to do that?') }));

Basically, the "prevent default" is meant to intercept and do something else: the "confirm" is designed for use in ... well - confirming!

참고URL : https://stackoverflow.com/questions/1551389/how-to-unbind-a-listener-that-is-calling-event-preventdefault-using-jquery

반응형