event.stopPropagation과 event.preventDefault의 차이점은 무엇입니까?
그들은 똑같은 일을하는 것 같습니다. 하나는 현대적이고 하나는 오래된 것입니까? 아니면 다른 브라우저에서 지원됩니까?
프레임 워크없이 이벤트를 직접 처리 할 때 항상 둘 다 확인하고 둘 다 있으면 실행합니다. (나도 return false
,하지만 첨부 된 이벤트와 함께 작동하지 않는 느낌이 듭니다 node.addEventListener
).
그렇다면 왜 둘 다? 둘 다 계속 확인해야합니까? 아니면 실제로 차이가 있습니까?
(나는 많은 질문을 안다. 그러나 그것들은 모두 똑같다 =))
stopPropagation
이벤트가 이벤트 체인에서 버블 링되는 것을 중지합니다.
preventDefault
브라우저가 해당 이벤트에 대해 수행하는 기본 작업을 방지합니다.
예
preventDefault
$("#but").click(function (event) {
event.preventDefault()
})
$("#foo").click(function () {
alert("parent click event fired!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="but">button</button>
</div>
stopPropagation
$("#but").click(function (event) {
event.stopPropagation()
})
$("#foo").click(function () {
alert("parent click event fired!")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="but">button</button>
</div>
함께 stopPropagation
만 button
의 클릭 핸들러는 그동안라고 div
의 클릭 핸들러는 ' 결코 발생합니다.
를 사용하는 것처럼 preventDefault
브라우저의 기본 작업 만 중지되지만 div의 클릭 핸들러는 계속 실행됩니다.
다음은 MDN의 DOM 이벤트 속성 및 메서드에 대한 문서입니다.
IE9 및 FF의 경우 preventDefault 및 stopPropagation을 사용할 수 있습니다.
IE8을 지원하고 대체 내리기 stopPropagation
로 cancelBubble
와 교체 preventDefault
로returnValue
술어
에서 quirksmode.org :
이벤트 캡처
이벤트 캡처를 사용하는 경우
| | --------------- | | ----------------- | element1 | | | | ----------- | | ----------- | | | element2 \ / | | | ------------------------- | | 이벤트 캡처 | -----------------------------------element1의 이벤트 핸들러가 먼저 실행되고 element2의 이벤트 핸들러가 마지막에 실행됩니다.
이벤트 버블 링
이벤트 버블 링을 사용할 때
/ \ --------------- | | ----------------- | element1 | | | | ----------- | | ----------- | | | element2 | | | | | ------------------------- | | 이벤트 버블 링 | -----------------------------------element2의 이벤트 핸들러가 먼저 실행되고 element1의 이벤트 핸들러가 마지막에 실행됩니다.
W3C 이벤트 모델에서 발생하는 모든 이벤트는 대상 요소에 도달 할 때까지 먼저 캡처 된 다음 다시 버블 링됩니다 .
| | / \ ----------------- | |-| | ----------------- | element1 | | | | | | ------------- | |-| | ----------- | | | element2 \ / | | | | | -------------------------------- | | W3C 이벤트 모델 | ------------------------------------------
상호 작용
에서 w3.org 를 들어, 이벤트 캡처 :
캡처
EventListener
가 이벤트의 추가 처리를 방지하려는 경우 인터페이스 의stopPropagation
메서드를 호출 할 수Event
있습니다. 이렇게하면EventListeners
동일한 계층 수준에 추가로 등록 된 경우에도 이벤트가 더 이상 전달되지 않습니다 . 이벤트의stopPropagation
메서드가 호출되면 해당 메서드에 대한 추가 호출은 추가 효과가 없습니다. 추가 캡처 프로그램stopPropagation
이없고 호출되지 않은 경우 이벤트EventListeners
는 대상 자체 에서 해당 항목 을 트리거합니다 .
대한 이벤트 버블 링 :
모든 이벤트 처리기는 인터페이스 의
stopPropagation
메서드를 호출하여 추가 이벤트 전파를 방지하도록 선택할 수 있습니다Event
. 어떤 경우EventListener
이 메소드를 호출, 모든 추가EventListeners
현재에는EventTarget
트리거하지만 그 수준에서 중단됩니다 버블 링됩니다.stopPropagation
더 이상 버블 링을 방지하기 위해에 대한 호출 은 한 번만 필요합니다.
대한 이벤트 취소 :
취소는
Event
의preventDefault
메서드 를 호출하여 수행됩니다 . 이벤트 흐름 단계에서 하나 이상의EventListeners
호출이preventDefault
발생하면 기본 작업이 취소됩니다.
예
다음 예제에서 웹 브라우저의 하이퍼 링크를 클릭하면 이벤트의 흐름 (이벤트 리스너가 실행 됨)과 이벤트 대상의 기본 작업 (새 탭이 열림)이 트리거됩니다.
HTML :
<div id="a">
<a id="b" href="http://www.google.com/" target="_blank">Google</a>
</div>
<p id="c"></p>
자바 스크립트 :
var el = document.getElementById("c");
function capturingOnClick1(ev) {
el.innerHTML += "DIV event capture<br>";
}
function capturingOnClick2(ev) {
el.innerHTML += "A event capture<br>";
}
function bubblingOnClick1(ev) {
el.innerHTML += "DIV event bubbling<br>";
}
function bubblingOnClick2(ev) {
el.innerHTML += "A event bubbling<br>";
}
// The 3rd parameter useCapture makes the event listener capturing (false by default)
document.getElementById("a").addEventListener("click", capturingOnClick1, true);
document.getElementById("b").addEventListener("click", capturingOnClick2, true);
document.getElementById("a").addEventListener("click", bubblingOnClick1, false);
document.getElementById("b").addEventListener("click", bubblingOnClick2, false);
예 1 : 결과가 출력됩니다.
DIV event capture
A event capture
A event bubbling
DIV event bubbling
예제 2 : stopPropagation()
함수에 추가
function capturingOnClick1(ev) {
el.innerHTML += "DIV event capture<br>";
ev.stopPropagation();
}
출력 결과
DIV event capture
이벤트 리스너가 이벤트의 더 이상 하향 및 상향 전파를 방지했습니다. 그러나 기본 동작 (새 탭 열기)을 막지는 못했습니다.
예제 3 : stopPropagation()
함수에 추가
function capturingOnClick2(ev) {
el.innerHTML += "A event capture<br>";
ev.stopPropagation();
}
또는 기능
function bubblingOnClick2(ev) {
el.innerHTML += "A event bubbling<br>";
ev.stopPropagation();
}
출력 결과
DIV event capture
A event capture
A event bubbling
두 이벤트 리스너가 동일한 이벤트 대상에 등록되어 있기 때문입니다. 이벤트 리스너가 이벤트의 상향 전파를 차단했습니다. 그러나 그들은 기본 동작 (새 탭 열기)을 막지 않았습니다.
예 4 : 예preventDefault()
를 들어 함수에 추가
function capturingOnClick1(ev) {
el.innerHTML += "DIV event capture<br>";
ev.preventDefault();
}
새 탭이 열리지 않도록합니다.
거짓 반환;
return false;
당신이 그것을 부를 때 3 개의 다른 일을합니다 :
event.preventDefault()
– 브라우저의 기본 동작을 중지합니다.event.stopPropagation()
– 이벤트가 DOM을 전파 (또는 "버블 링")하는 것을 방지합니다.- 콜백 실행을 중지하고 호출시 즉시 반환합니다.
이 동작은 일반적인 (jQuery가 아닌) 이벤트 핸들러와 다르며, 특히 return false
이벤트가 버블 링되는 것을 중지하지 않습니다.
preventDefault ();
preventDefault();
한 가지를 수행합니다. 브라우저의 기본 동작을 중지합니다.
언제 사용합니까?
우리는 그들이 무엇을하는지 알고 있지만 언제 사용해야합니까? 단순히 달성하고자하는 것에 달려 있습니다. preventDefault();
기본 브라우저 동작을 "단지"방지하려는 경우 사용 합니다. 반환 거짓 사용; 기본 브라우저 동작을 방지하고 이벤트가 DOM을 전파하지 못하도록하려는 경우. 사용하는 대부분의 상황에서 return false; 당신이 정말로 원하는 것은 preventDefault()
.
예 :
예를 들어 이해해 봅시다.
순수한 JAVASCRIPT 예제를 볼 것입니다.
예 1 :
<div onclick='executeParent()'>
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
function executeChild() {
alert('Link Clicked');
}
function executeParent() {
alert('div Clicked');
}
</script>
위의 코드를 실행하면 '여기를 클릭하여 stackoverflow.com을 방문하십시오' 라는 하이퍼 링크가 표시 됩니다. 해당 링크를 먼저 클릭하면 자바 스크립트 알림이 표시됩니다. 링크 클릭 됨 다음으로 자바 스크립트 알림 div가 클릭 되고 즉시 리디렉션됩니다. stackoverflow.com.
예 2 :
<div onclick='executeParent()'>
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
function executeChild() {
event.preventDefault();
event.currentTarget.innerHTML = 'Click event prevented'
alert('Link Clicked');
}
function executeParent() {
alert('div Clicked');
}
</script>
위의 코드를 실행하면 '여기를 클릭하여 stackoverflow.com을 방문하십시오'라는 하이퍼 링크가 표시됩니다. 해당 링크를 먼저 클릭하면 자바 스크립트 알림이 표시됩니다. 링크 클릭 됨 다음은 자바 스크립트 알림 div 가 표시됩니다. 클릭 됨 다음은 하이퍼 링크 ' 여기를 클릭하여 stackoverflow.com을 방문하십시오 .'Click event prevented '텍스트로 바뀌면 stackoverflow.com 으로 리디렉션 되지 않습니다 . 이는 기본 클릭 동작이 트리거되는 것을 방지하기 위해 사용한 event.preventDefault () 메서드 때문입니다.
예 3 :
<div onclick='executeParent()'>
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
function executeChild() {
event.stopPropagation();
event.currentTarget.innerHTML = 'Click event prevented'
alert('Link Clicked');
}
function executeParent() {
alert('div Clicked');
}
</script>
이번에는 Link를 클릭하면 executeParent () 함수가 호출되지 않으며 이번에 는 javascript 경고 div Clicked 가 표시되지 않습니다 . 이는 event.stopPropagation () 메서드를 사용하여 부모 div 로의 전파를 막았 기 때문입니다. 다음으로 'Click event is going to be execute'텍스트로 대체 된 'Click here to visit stackoverflow.com'하이퍼 링크가 표시되고 즉시 stackoverflow.com으로 리디렉션됩니다. 이는 event.preventDefault () 메서드를 사용하여 이번에는 기본 클릭 동작이 트리거되는 것을 막지 않았기 때문입니다.
예 4 :
<div onclick='executeParent()'>
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
function executeChild() {
event.preventDefault();
event.stopPropagation();
event.currentTarget.innerHTML = 'Click event prevented'
alert('Link Clicked');
}
function executeParent() {
alert('Div Clicked');
}
</script>
If you click on the Link, the function executeParent() will not be called and you will not get the javascript alert. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is because we have prevented the default click action from triggering this time using event.preventDefault() method.
Example 5:
For return false I have three examples and all appear to be doing the exact same thing (just returning false), but in reality the results are quite different. Here's what actually happens in each of the above.
cases:
- Returning false from an inline event handler prevents the browser from navigating to the link address, but it doesn't stop the event from propagating through the DOM.
- Returning false from a jQuery event handler prevents the browser from navigating to the link address and it stops the event from propagating through the DOM.
- Returning false from a regular DOM event handler does absolutely nothing.
Will see all three example.
- Inline return false.
<div onclick='executeParent()'>
<a href='https://stackoverflow.com' onclick='return false'>Click here to visit stackoverflow.com</a>
</div>
<script>
var link = document.querySelector('a');
link.addEventListener('click', function() {
event.currentTarget.innerHTML = 'Click event prevented using inline html'
alert('Link Clicked');
});
function executeParent() {
alert('Div Clicked');
}
</script>
- Returning false from a jQuery event handler.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a href='https://stackoverflow.com'>Click here to visit stackoverflow.com</a>
</div>
<script>
$('a').click(function(event) {
alert('Link Clicked');
$('a').text('Click event prevented using return FALSE');
$('a').contents().unwrap();
return false;
});
$('div').click(function(event) {
alert('Div clicked');
});
</script>
- Returning false from a regular DOM event handler.
<div onclick='executeParent()'>
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>
</div>
<script>
function executeChild() {
event.currentTarget.innerHTML = 'Click event prevented'
alert('Link Clicked');
return false
}
function executeParent() {
alert('Div Clicked');
}
</script>
Hope these examples are clear. Try executing all these examples in a html file to see how they work.
This is the quote from here
Event.preventDefault
The preventDefault method prevents an event from carrying out its default functionality. For example, you would use preventDefault on an A element to stop clicking that element from leaving the current page:
//clicking the link will *not* allow the user to leave the page
myChildElement.onclick = function(e) {
e.preventDefault();
console.log('brick me!');
};
//clicking the parent node will run the following console statement because event propagation occurs
logo.parentNode.onclick = function(e) {
console.log('you bricked my child!');
};
While the element's default functionality is bricked, the event continues to bubble up the DOM.
Event.stopPropagation
The second method, stopPropagation, allows the event's default functionality to happen but prevents the event from propagating:
//clicking the element will allow the default action to occur but propagation will be stopped...
myChildElement.onclick = function(e) {
e.stopPropagation();
console.log('prop stop! no bubbles!');
};
//since propagation was stopped by the child element's onClick, this message will never be seen!
myChildElement.parentNode.onclick = function(e) {
console.log('you will never see this message!');
};
stopPropagation effectively stops parent elements from knowing about a given event on its child.
While a simple stop method allows us to quickly handle events, it's important to think about what exactly you want to happen with bubbling. I'd bet that all a developer really wants is preventDefault 90% of the time! Incorrectly "stopping" an event could cause you numerous troubles down the line; your plugins may not work and your third party plugins could be bricked. Or worse yet -- your code breaks other functionality on a site.
event.preventDefault();
Stops the default action of an element from happening.
event.stopPropagation();
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
For example, if there is a link with a click method attached inside of a DIV
or FORM
that also has a click method attached, it will prevent the DIV
or FORM
click method from firing.
Event.preventDefault- stops browser default behaviour. Now comes what is browser default behaviour. Assume you have a anchor tag and it has got a href attribute and this anchor tag is nested inside a div tag which has got a click event. Default behaviour of anchor tag is when clicked on the anchor tag it should navigate, but what event.preventDefault does is it stops the navigation in this case. But it never stops the bubbling of event or escalation of event i.e
<div class="container">
<a href="#" class="element">Click Me!</a>
</div>
$('.container').on('click', function(e) {
console.log('container was clicked');
});
$('.element').on('click', function(e) {
e.preventDefault(); // Now link won't go anywhere
console.log('element was clicked');
});
The result will be
"element was clicked"
"container was clicked"
Now event.StopPropation it stops bubbling of event or escalation of event. Now with above example
$('.container').on('click', function(e) {
console.log('container was clicked');
});
$('.element').on('click', function(e) {
e.preventDefault(); // Now link won't go anywhere
e.stopPropagation(); // Now the event won't bubble up
console.log('element was clicked');
});
Result will be
"element was clicked"
For more info refer this link https://codeplanet.io/preventdefault-vs-stoppropagation-vs-stopimmediatepropagation/
$("#but").click(function(event){
console.log("hello");
event.preventDefault();
});
$("#foo").click(function(){
alert("parent click event fired !");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="but">button</button>
</div>
'Nice programing' 카테고리의 다른 글
Git에서 단일 브랜치를 어떻게 복제합니까? (0) | 2020.09.29 |
---|---|
C #에서 문자를 반복하는 가장 좋은 방법 (0) | 2020.09.29 |
커밋 메시지로 Git 저장소를 검색하는 방법은 무엇입니까? (0) | 2020.09.29 |
git은 커밋되지 않았거나 저장되지 않은 모든 변경 사항을 실행 취소합니다. (0) | 2020.09.29 |
NaN 값을 어떻게 확인할 수 있습니까? (0) | 2020.09.28 |