AddEvenListener()-2

조익준·2023년 4월 16일
0

Javascript

목록 보기
12/16

박스를 누르면 노란색으로 바뀌는 함수를 만들어보자.

1. for문을 활용

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>박스 색 바꾸기</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            border: 1px solid red;
            cursor: pointer;
        }
        .wrapper{
            display: flex;
        }
    </style>
</head>
<body>
    <h1>원하는 박스를 클릭해보세요</h1>
    <div class="wrapper">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
        <div class="box">box4</div>
        <div class="box">box5</div>
        <div class="box">box6</div>
        <div class="box">box7</div>
        <div class="box">box8</div>
        <div class="box">box9</div>
        <div class="box">box10</div>
    </div>
    <script>
        let arr = document.querySelectorAll(".box");
       
        for(let i=0; i<arr.length; i++) {
            arr[i].addEventListener("click", () => {
            arr[i].style.backgroundColor = "yellow";
            2번째줄의 arr[i]를 e.target으로 바꿔도 상관x
            })
        }
    </script>
</body>
</html>

2. forEach() 이용

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            border: 1px solid red;
            cursor: pointer;
        }
        .wrapper{
            display: flex;
        }
    </style>
</head>
<body>
    <h1>원하는 박스를 클릭해보세요</h1>
    <div class="wrapper">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
        <div class="box">box4</div>
        <div class="box">box5</div>
        <div class="box">box6</div>
        <div class="box">box7</div>
        <div class="box">box8</div>
        <div class="box">box9</div>
        <div class="box">box10</div>
    </div>
    <script>
        let arr = document.querySelectorAll(".box");
       
        // for(let i=0; i<arr.length; i++) {
        //     arr[i].addEventListener("click", (e) => {
        //     e.target.style.backgroundColor = "yellow";
        //     })
        // }

        arr.forEach(function(item, index){
            document.querySelectorAll(".box")[index].addEventListener("click", (e) => {
                e.target.style.backgroundColor = "yellow";
            })
        });
    </script>
</body>
</html>
profile
비가역적인사람

0개의 댓글