簡體   English   中英

如何將事件設置為通過.classList.add添加類的選擇器

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

我想在下面得到結果,但不知道如何。

  1. 通過單擊按鈕將框顏色從黃色更改為紅色。
  2. 單擊紅色框顯示警報。

第一個適用於我的代碼。 但是第二個不起作用。

有人可以幫我嗎?

<!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>

問題是,當您那時附加第二個偵聽器時,不存在class = red元素。

您應該將onclick事件更改為第一個事件中的第二個事件,在這種情況下,請勿使用addEventListener。

 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM