IT박스

evt.preventDefault ()의 반대는 무엇입니까?

itboxs 2020. 6. 4. 20:07
반응형

evt.preventDefault ()의 반대는 무엇입니까?


를 해고하면 evt.preventDefault()기본 작업을 다시 재개 하려면 어떻게해야합니까?


@Prescott의 의견에 따르면 다음과 반대입니다.

evt.preventDefault();

될 수 있습니다 :

더 이상 방해하지 않기 때문에 기본적으로 '기본 설정'동일시 합니다.

그렇지 않으면 다른 의견과 답변에서 제공하는 답변을 알려줍니다.

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

event.preventDefault를 다시 활성화하는 방법?

두 번째 솔루션은 redsquare이 제공 한 예제 솔루션으로 승인되었습니다 (이것이 중복으로 닫히지 않은 경우 직접 솔루션을 위해 여기에 게시 됨).

$('form').submit( function(ev) {
     ev.preventDefault();
     //later you decide you want to submit
     $(this).unbind('submit').submit()
});

function(evt) {evt.preventDefault();}

그리고 그 반대

function(evt) {return true;}

건배!


clickjQuery 이벤트에서 링크를 계속하기 전에 명령을 처리하려면 다음을 수행하십시오 .

예 : <a href="http://google.com/" class="myevent">Click me</a>

jQuery를 방지하고 따르십시오.

$('a.myevent').click(function(event) {
    event.preventDefault();

    // Do my commands
    if( myEventThingFirst() )
    {
      // then redirect to original location
      window.location = this.href;
    }
    else
    {
      alert("Couldn't do my thing first");
    }
});

또는 단순히 실행 window.location = this.href;애프터preventDefault();


event.preventDefault(); //or event.returnValue = false;

그 반대 (표준) :

event.returnValue = true;

출처 : https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue


확인 ! 클릭 이벤트에서 작동합니다.

$("#submit").click(function(e){ 

   e.preventDefault();

  -> block the click of the sumbit ... do what you want

$("#submit").unbind('click').click(); // the html click submit work now !

});

비동기 호출을 실행하기 위해 jQuery에서 양식 제출을 지연해야했습니다. 간단한 코드는 다음과 같습니다.

$("$theform").submit(function(e) {
    e.preventDefault();
    var $this = $(this);
    $.ajax('/path/to/script.php',
        {
        type: "POST",
        data: { value: $("#input_control").val() }
    }).done(function(response) {
        $this.unbind('submit').submit();
    });
});

다음과 같은 패턴을 제안합니다.

document.getElementById("foo").onsubmit = function(e) {
    if (document.getElementById("test").value == "test") {
        return true;
    } else {
        e.preventDefault();
    }
}

<form id="foo">
    <input id="test"/>
    <input type="submit"/>
</form>

... 내가 뭔가를 빠뜨리지 않는 한.

http://jsfiddle.net/DdvcX/


event.preventDefault()왜 당신이 event.preventDefault()그것을 부를 때 무엇을 조사해야하는지 이해하는 반대의 방법은 없습니다 .

Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution. If you’re familiar with the old ways of Javascript, it was once in fashion to use return false for canceling events on things like form submits and buttons using return true (before jQuery was even around).

As you probably might have already worked out based on the simple explanation above: the opposite of event.preventDefault() is nothing. You just don’t prevent the event, by default the browser will allow the event if you are not preventing it.

See below for an explanation:

;(function($, window, document, undefined)) {

    $(function() {
        // By default deny the submit
        var allowSubmit = false;

        $("#someform").on("submit", function(event) {

            if (!allowSubmit) {
                event.preventDefault();

                // Your code logic in here (maybe form validation or something)
                // Then you set allowSubmit to true so this code is bypassed

                allowSubmit = true;
            }

        });
    });

})(jQuery, window, document);

In the code above you will notice we are checking if allowSubmit is false. This means we will prevent our form from submitting using event.preventDefault and then we will do some validation logic and if we are happy, set allowSubmit to true.

This is really the only effective method of doing the opposite of event.preventDefault() – you can also try removing events as well which essentially would achieve the same thing.


Here's something useful...

First of all we'll click on the link , run some code, and than we'll perform default action. This will be possible using event.currentTarget Take a look. Here we'll gonna try to access Google on a new tab, but before we need to run some code.

<a href="https://www.google.com.br" target="_blank" id="link">Google</a>

<script type="text/javascript">
    $(document).ready(function() {
        $("#link").click(function(e) {

            // Prevent default action
            e.preventDefault();

            // Here you'll put your code, what you want to execute before default action
            alert(123); 

            // Prevent infinite loop
            $(this).unbind('click');

            // Execute default action
            e.currentTarget.click();
        });
    });
</script>

This is what I used to set it:

$("body").on('touchmove', function(e){ 
    e.preventDefault(); 
});

And to undo it:

$("body").unbind("touchmove");

I supose the "opposite" would be to simulate an event. You could use .createEvent()

Following Mozilla's example:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var cancelled = !cb.dispatchEvent(evt);
  if(cancelled) {
    // A handler called preventDefault
    alert("cancelled");
  } else {
    // None of the handlers called preventDefault
    alert("not cancelled");
  }
}

Ref: document.createEvent


jQuery has .trigger() so you can trigger events on elements -- sometimes useful.

$('#foo').bind('click', function() {
      alert($(this).text());
});

$('#foo').trigger('click');

jquery on() could be another solution to this. escpacially when it comes to the use of namespaces.

jquery on() is just the current way of binding events ( instead of bind() ). off() is to unbind these. and when you use a namespace, you can add and remove multiple different events.

$( selector ).on("submit.my-namespace", function( event ) {
    //prevent the event
    event.preventDefault();

    //cache the selector
    var $this = $(this);

    if ( my_condition_is_true ) {
        //when 'my_condition_is_true' is met, the binding is removed and the event is triggered again.
        $this.off("submit.my-namespace").trigger("submit");
    }
});

now with the use of namespace, you could add multiple of these events and are able to remove those, depending on your needs.. while submit might not be the best example, this might come in handy on a click or keypress or whatever..


you can use this after "preventDefault" method

//Here evt.target return default event (eg : defult url etc)

var defaultEvent=evt.target;

//Here we save default event ..

if("true")
{
//activate default event..
location.href(defaultEvent);
}

You can always use this attached to some click event in your script:

location.href = this.href;

example of usage is:

jQuery('a').click(function(e) {
    location.href = this.href;
});

None of the solutions helped me here and I did this to solve my situation.

<a onclick="return clickEvent(event);" href="/contact-us">

And the function clickEvent(),

function clickEvent(event) {
    event.preventDefault();
    // do your thing here

    // remove the onclick event trigger and continue with the event
    event.target.parentElement.onclick = null;
    event.target.parentElement.click();
}

I have used the following code. It works fine for me.

$('a').bind('click', function(e) {
  e.stopPropagation();
});

this code worked for me to re-instantiate the event after i had used :

event.preventDefault(); to disable the event.


event.preventDefault = false;

참고URL : https://stackoverflow.com/questions/5651933/what-is-the-opposite-of-evt-preventdefault

반응형