简体   繁体   中英

How to set event to the Selector which is added class with .classList.add

I want to get result below but don't know how.

  1. change box colors yellow to red by clicking button.
  2. show alert by clicking red box.

1st one works with my code. But the 2nd one doesn't work.

Could someone help me with this?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color:yellow;
        }
        .box.red {
            background-color: red;
        }
    </style>
</head>
<body>
    <a href="#" class="button">Click</a>
    <div class="box">BOX</div>

    <script>
        document.querySelector('.button').addEventListener('click', () => {
           document.querySelector('.box').classList.add('red');
        });

        document.querySelector('.box.red').addEventListener('click', () => {
            window.alert('You clicked Red Box');
        });
    </script>

</body>
</html>

The problem is this when you attach second listener at that time there is no element with class = red .

You should change the onclick event to second one inside first one and don't use addEventListener in this case.

 let btn = document.querySelector('.button'); btn.onclick = function(){ document.querySelector('.box').classList.add('red'); document.querySelector('.red').onclick = function(){ window.alert('You clicked Red Box'); } } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box { width: 100px; height: 100px; background-color:yellow; } .box.red { background-color: red; } </style> </head> <body> <a href="#" class="button">Click</a> <div class="box">BOX</div> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM