Programing

event.preventDefault () 대 반환 false (jQuery 없음)

lottogame 2020. 10. 13. 07:18
반응형

event.preventDefault () 대 반환 false (jQuery 없음)


나는 궁금 event.preventDefault()return false동일 하였다.

나는 짓을 몇 가지 테스트를 , 그것은 보인다

  • 예를 들어 이전 모델을 사용하여 이벤트 핸들러를 추가 한 경우

    elem.onclick = function(){
        return false;
    };
    

    그런 다음, return false방지의 기본 동작처럼 event.preventDefault().

  • addEventListener예를 들어를 사용하여 이벤트 핸들러를 추가 한 경우

    elem.addEventListener(
        'click',
        function(e){
            return false;
        },
        false
    );
    

    그런 다음 return false기본 작업을 방지하지 않습니다.

모든 브라우저가 이와 같이 작동합니까?

event.preventDefault()사이에 더 많은 차이점이 return false있습니까?

어떤 경우 return false와 같은 동작 에 대한 문서 (MDN에 없습니다)를 어디서 찾을 수 있습니까 event.preventDefault()?


내 질문은 jQuery가 아닌 일반 자바 스크립트에 관한 것이므로 두 질문이 거의 같은 제목을 가지고 있더라도 event.preventDefault () 대 return false 의 중복으로 표시하지 마십시오 .


W3C 문서 객체 모델 이벤트 사양1.3.1. 이벤트 등록 인터페이스handleEvent 는 EventListener에 반환 값이 없다고 명시합니다 .

handleEvent이 메소드는 EventListener 인터페이스가 등록 된 유형의 이벤트가 발생할 때마다 호출됩니다. [...] 반환 값 없음

1.2.4 미만 . 이벤트 취소 문서에는

취소는 이벤트의 preventDefault 메서드를 호출하여 수행됩니다. 하나 이상의 EventListeners가 이벤트 흐름 단계에서 preventDefault를 호출하면 기본 작업이 취소됩니다.

이것은 true / false를 반환하는 결과가 어떤 브라우저에서나 사용할 수있는 효과를 사용하지 못하게합니다 event.preventDefault().

최신 정보

HTML5 사양은 실제로 반환 값을 다르게 처리하는 방법을 지정합니다. HTML 사양의 섹션 7.1.5.1에 따르면

반환 값이 WebIDL 부울 false 값이면 이벤트를 취소합니다.

"마우스 오버"이벤트를 제외한 모든 것.

결론

event.preventDefault()이전 사양 및 이전 브라우저와 호환되므로 대부분의 프로젝트에서 사용하는 것이 좋습니다 . 최첨단 브라우저 만 지원해야하는 경우에만 false를 반환하여 취소해도됩니다.


다음은 사람들이 문제를 더 잘 이해하고 해결하는 데 도움이 될 수있는 몇 가지 예입니다.

TL; DR

  • on*이벤트 핸들러 (예 onclick: 버튼 요소의 속성) : 이벤트를 취소하려면 false를 반환합니다.
  • addEventListener다른 API이므로 반환 값 (예 false:)은 무시됩니다. 사용 event.preventDefault().
  • onclick="<somejs>"<somejs>onclick 함수의 본문에 포함되어 있기 때문에 잠재적 인 혼란 이 있습니다.
  • 브라우저 devtools getEventListenersAPI를 사용 하여 이벤트 핸들러가 예상대로 작동하지 않는 경우 문제를 해결하기 위해 이벤트 리스너가 어떻게 보이는지 확인합니다.

이 예제는 링크 가있는 click이벤트 에만 해당 <a>되지만 대부분의 이벤트 유형에 대해 일반화 될 수 있습니다.

js-some-link-hook모달을 열고 페이지 탐색이 발생하지 않도록 방지하려는 클래스가있는 앵커 (링크)가 있습니다.

아래 예제는 MacOS Mojave의 google chrome (71)에서 실행되었습니다.

한 가지 주요 함정은 onclick=functionName사용하는 것과 동일한 동작을 가정하는 것 입니다.addEventListener

onclick 속성

function eventHandler (event) {
    // want to prevent link navigation
    alert('eventHandler ran');
    return false;
}

function addEventListenerToElement () {
    var link = document.querySelector('.js-some-link-hook');
    link.setAttribute('onclick', eventHandler);
}
addEventListenerToElement();

그런 다음 브라우저 devtools 콘솔에서 실행합니다.

var el = document.querySelector('a.js-some-link-hook'),
        listener = getEventListeners(el).click[0].listener;
    console.log(''+listener); // to avoid truncation of output

... 그리고 다음을 볼 수 있습니다.

function onclick(event) {
function t(n){return alert("eventHandler ran"),!1}
}

이것은 전혀 작동하지 않습니다. onclick=핸들러 함수를 사용할 때 다른 함수로 래핑됩니다. 이 경우 함수 정의가 포함되어 있지만 호출하지 않고 함수 참조를 지정했기 때문에 호출되지 않았 음을 알 수 있습니다. 또한 내 함수가 호출되고 내 함수가 false를 반환하더라도 onclick 함수는 이벤트를 '취소'하는 데 필요한 false 값을 반환하지 않습니다. 우리는 정말 필요한 return myHandlerFunc();일에 일을위한 온 클릭 기능에 싸여 할 수 있습니다.

이제 어떻게 작동하는지 확인 했으므로 원하는 작업을 수행하도록 코드를 수정할 수 있습니다. 예시를위한 이상한 예 (이 코드를 사용하지 마세요) :

function eventHandler (event) {
    // want to prevent link navigation
    alert('eventHandler ran');
    return false;
}

function addEventListenerToElement () {
    var link = document.querySelector('.js-some-link-hook');
    link.setAttribute('onclick', 'return ('+eventHandler+')();');
}
addEventListenerToElement();

eventHandler 함수 정의를 문자열로 래핑 한 것을 볼 수 있습니다. 특히 : 앞에 return 문이있는 자체 실행 함수입니다.

다시 크롬 devtools 콘솔에서 :

var el = document.querySelector('a.js-some-link-hook'),
        listener = getEventListeners(el).click[0].listener;
    console.log(''+listener); // to avoid truncation of output

... 표시 :

function onclick(event) {
return (function t(e){return alert("eventHandler ran"),!1})();
}

... 그래, 작동합니다. 우리 return false( !1최소화 실행으로 인해 죄송합니다). 링크를 클릭하면 경고가 표시되고 경고를 해제하면 페이지가 아무 곳도 탐색하지 않거나 새로 고쳐지지 않습니다.

addEventListener

function eventHandler (event) {
    // want to prevent link navigation
    alert('eventHandler ran');
    return false;
}

function addEventListenerToElement () {
    var link = document.querySelector('.js-some-link-hook');
    link.addEventListener('click', eventHandler, false);
}
addEventListenerToElement();

브라우저 개발 도구 :

var el = document.querySelector('a.js-some-link-hook'),
        listener = getEventListeners(el).click[0].listener;
    console.log(''+listener); // to avoid truncation of output

결과:

function e(n){return alert("eventHandler ran"),!1}

So you can already see the difference. We aren't wrapped in an onclick function. So our return false (return !1 due to minification) is at the top level here and we don't have to worry about adding an extra return statement like before.

So it looks like it should work. Clicking on the link we get the alert. Dismiss the alert and the page navigates/refreshes. ie the event was NOT cancelled by returning false.

If we lookup the spec (see resources at bottom), we see that our callback/handler function for addEventListener does not support a return type. We can return whatever we want, but since it isn't part of the interface, it doesn't have any effect.

Solution: using event.preventDefault() instead of return false;...

function eventHandler (event) {
    // want to prevent link navigation
    event.preventDefault();
    alert('eventHandler ran');
}

function addEventListenerToElement () {
    var link = document.querySelector('.js-some-link-hook');
    link.addEventListener('click', eventHandler, false);
}
addEventListenerToElement();

browser devtools...

var el = document.querySelector('a.js-some-link-hook'),
        listener = getEventListeners(el).click[0].listener;
    console.log(''+listener); // to avoid truncation of output

gives...

function n(e){e.preventDefault(),alert("eventHandler ran")}

...as expected.

Testing: get the alert. Dismiss alert. No page navigation or refresh...which is what we want.

Resources

The html5 spec (https://www.w3.org/TR/html5/webappapis.html#events) confuses things because they use both onclick and addEventListener in their examples and they say the following:

The event handler processing algorithm for an event handler H and an Event object E is as follows:

...

  1. Process return value as follows:

...

If return value is a Web IDL boolean false value, then cancel the event.

So it seems to imply that return false cancels the event for both addEventListener and onclick.

But, if you look at their linked definition of event-handler you see:

An event handler has a name, which always starts with "on" and is followed by the name of the event for which it is intended.

...

Event handlers are exposed in one of two ways.

The first way, common to all event handlers, is as an event handler IDL attribute.

The second way is as an event handler content attribute. Event handlers on HTML elements and some of the event handlers on Window objects are exposed in this way.

https://www.w3.org/TR/html5/webappapis.html#event-handler

So it seems that the return false cancelling the event really does only apply to the onclick (or generally on*) event handlers and not to event handlers registered via addEventListener which has a different API. Since the addEventListener API is not covered under the html5 spec and only the on* event handlers...it would be less confusing if they stuck to that in their examples and specifically called out the difference.


Difference between preventDefault, stopPropogation, return false

Table Showing Difference

Default Action – Server side action when control event raise.

Suppose we have div control and inside it we have a button. So div is the parent control of the button. We have Client side click and server side click event of the button. Also we have client side click event of the div.

On click event of the button on client side, we can control the actions of parent control and server side code using following three ways:

  • return false - This allow only client side event of the control. Server side event and client side event of the parent control is not fired.

  • preventDefault() - This allow client side event of control and its parent control. Server side event ie. Default action of the control is not fired.

  • stopPropogation() – This allow client side as well as server side event of the control. Client side event of the control is notallowed.


return false is just for IE, event.preventDefault() is supported by chrome,ff... modern browsers

참고URL : https://stackoverflow.com/questions/18971284/event-preventdefault-vs-return-false-no-jquery

반응형