KOSTA/HTML
21.06.18 - JavaScript 이벤트 버블링
놀코
2021. 6. 18. 14:33
1. 클릭 이벤트 중첩 (이벤트 버블링)
<!DOCTYPE html>
<html>
<body>
<div
style="
background-color: yellow;
width: 500px;
height: 300px;
border: 1px solid;
"
>
<a href="http://www.daum.net">다음카카오</a>
</div>
</body>
<script>
// a태그는 click 이벤트 , form태그는 submit 이벤트가 기본 내장되어있음.
var aObj = document.querySelector('div>a');
aObj.addEventListener('click', function (event) {
aObj.style.backgroundColor = 'gray';
event.preventDefault();
event.stopPropagation(); //이벤트 버블링 방지
});
var divObj = document.querySelector('div'); //자식쪽에서 발생된 이벤트가 부모 요소에 전달이된다. 함께 클릭 이벤트 진행됨..
divObj.addEventListener('click', function () {
divObj.style.backgroundColor = 'pink';
});
</script>
</html>
jQuery로 코딩했을경우....
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div
style="
background-color: yellow;
width: 500px;
height: 300px;
border: 1px solid;
"
>
<a href="http://www.daum.net">다음카카오</a>
</div>
</body>
<script>
// a태그는 click 이벤트 , form태그는 submit 이벤트가 기본 내장되어있음.
var $aObj = $('div>a');
$aObj.click(function (event) {
$aObj.css('background-color', 'gray');
// event.preventDefault();
// event.stopPropagation(); //이벤트 버블링 방지
return false;
});
var divObj = document.querySelector('div'); //자식쪽에서 발생된 이벤트가 부모 요소에 전달이된다. 함께 클릭 이벤트 진행됨..
divObj.addEventListener('click', function () {
divObj.style.backgroundColor = 'pink';
});
</script>
</html>
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() { //3: 응답후 처리
document.getElementById("demo").innerHTML =
this.responseText; //응답결과
}
xhttp.open("GET", "ajax_info.txt"); //1: 요청정보
xhttp.send(); //2 : 요청
}
</script>
</body>
</html>
출처 예제 : https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_first