확인란 클릭 시 이벤트 버블링을 중지하는 방법
클릭 이벤트에 대해 Ajax 액션을 실행하는 체크박스가 있지만, 체크박스를 클릭했을 때 실행하고 싶지 않은 자체 클릭 동작이 있는 컨테이너에도 체크박스가 있습니다.이 샘플은 무엇을 하고 싶은지 나타내고 있습니다.
$(document).ready(function() {
$('#container').addClass('hidden');
$('#header').click(function() {
if ($('#container').hasClass('hidden')) {
$('#container').removeClass('hidden');
} else {
$('#container').addClass('hidden');
}
});
$('#header input[type=checkbox]').click(function(event) {
// Do something
});
});
#container.hidden #body {
display: none;
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="container">
<div id="header">
<h1>Title</h1>
<input type="checkbox" name="test" />
</div>
<div id="body">
<p>Some content</p>
</div>
</div>
그러나 기본 클릭 동작(체크박스가 켜지거나 꺼짐)을 실행하지 않고는 이벤트 버블링을 정지할 수 없습니다.
다음 두 가지 모두 이벤트 버블링을 중지하지만 확인란 상태도 변경하지 않습니다.
event.preventDefault();
return false;
교체하다
event.preventDefault();
return false;
와 함께
event.stopPropagation();
event.stopPropagation()
부모 요소에 대한 이벤트 버블링을 중지하고 부모 핸들러가 이벤트를 알리지 않도록 합니다.
event.provent Default()
브라우저가 기본 작업을 실행할 수 없도록 합니다.메서드 isDefaultPrevented 를 사용하여 (이벤트 오브젝트에서) 이 메서드가 호출되었는지 여부를 확인합니다.
stopPropagation 메서드를 사용합니다.
event.stopPropagation();
IE를 잊지 마세요.
if (event.stopPropagation) { // standard
event.stopPropagation();
} else { // IE6-8
event.cancelBubble = true;
}
다른 사람들이 언급했듯이,stopPropagation()
.
그리고 두 번째 핸들러가 있습니다.event.cancelBubble = true;
IE 고유의 핸들러이지만 적어도 FF에서 지원됩니다.저도 써본 적이 없기 때문에 잘 모르지만, 다른 모든 것이 실패한다면 시도해 볼 가치가 있을지도 모릅니다.
jQuery를 사용하는 경우 중지 함수를 별도로 호출할 필요가 없습니다.
그냥 돌아가면 돼false
이벤트 핸들러에서
그러면 이벤트가 중지되고 거품이 꺼집니다.
event.proventDefault()와 return false도 참조해 주세요.
jQuery 문서에서:
따라서 이러한 핸들러는 위임된 핸들러가 호출함으로써 트리거되지 않도록 할 수 있습니다.
event.stopPropagation()
또는 되돌아가다false
.
이는 이벤트 버블링 개념을 이해하기 위한 훌륭한 예입니다.위의 답변을 바탕으로 최종 코드는 다음과 같습니다.사용자가 체크박스를 클릭하면 상위 요소인 'header'에 대한 이벤트 전파가 중지됩니다.event.stopPropagation();
.
$(document).ready(function() {
$('#container').addClass('hidden');
$('#header').click(function() {
if($('#container').hasClass('hidden')) {
$('#container').removeClass('hidden');
} else {
$('#container').addClass('hidden');
}
});
$('#header input[type=checkbox]').click(function(event) {
if (event.stopPropagation) { // standard
event.stopPropagation();
} else { // IE6-8
event.cancelBubble = true;
}
});
});
코드에 대한 크레딧은 @mehras에 있습니다.이 기능을 사용해 볼 수 있는 핑계를 찾고 싶었기 때문에 시연하기 위해 스니펫을 작성했습니다.
$(document).ready(function() {
$('#container').addClass('hidden');
$('#header').click(function() {
if ($('#container').hasClass('hidden')) {
$('#container').removeClass('hidden');
} else {
$('#container').addClass('hidden');
}
});
$('#header input[type=checkbox]').click(function(event) {
if (event.stopPropagation) { // standard
event.stopPropagation();
} else { // IE6-8
event.cancelBubble = true;
}
});
});
div {
text-align: center;
padding: 2em;
font-size: 1.2em
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="header"><input type="checkbox" />Checkbox won't bubble the event, but this text will.</div>
<div id="container">click() bubbled up!</div>
여기 나에게 효과가 있었던 요령이 있다.
handleClick = e => {
if (e.target === e.currentTarget) {
// do something
} else {
// do something else
}
}
설명:첨부했습니다handleClick
모달 창을 배경으로 하지만 모달 창을 클릭할 때마다(background div에 있었기 때문에) 켜집니다.그래서 조건을 붙였습니다.(e.target === e.currentTarget)
이 기능은 배경을 클릭했을 때만 실행됩니다.
angularjs에서는 다음과 같이 동작해야 합니다.
event.preventDefault();
event.stopPropagation();
언급URL : https://stackoverflow.com/questions/1164213/how-to-stop-event-bubbling-on-checkbox-click
'programing' 카테고리의 다른 글
JSON 문자열을 어레이로 변환하는 방법 (0) | 2022.10.02 |
---|---|
날짜가 30일 이상인지 확인하다 (0) | 2022.10.02 |
POST 본문을 php로 가져오려면 어떻게 해야 하나요? (0) | 2022.10.02 |
조건과 일치하는 배열 내 개체의 인덱스를 가져옵니다. (0) | 2022.10.02 |
Java에서의 Fail-safe 및 Fail-Fast Iterator란 무엇입니까? (0) | 2022.09.30 |