Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

selectors api - querySelectorAll's click button issue

Anyone know why the below code is not working? suppose the website will get back something if i click the arrow button, any code i typed wrong in querySelectorAll? many thanks!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==" crossorigin="anonymous" />
    <style>
        .buttons {
            font-size: 48px;
        }
    </style>
</head>
<body>
    <h1>Dance Time</h1>    
    <div class="buttons"></div>
    <i class="fas fa-arrow-up"></i>
    <i class="fas fa-arrow-down"></i>
    <i class="fas fa-arrow-left"></i>
    <i class="fas fa-arrow-right"></i>
    </div>
    <script>
        let arrows = document.querySelectorAll('.buttons .fas')
        for (const arrow of arrows) {
            arrow.addEventListener('click',function(){
                if (arrow.classList.contains('fa-arrow-up')) {  
            console.log('arrow clicked')
                }
        })
        }
    </script>
</body>
</html>
question from:https://stackoverflow.com/questions/65546691/queryselectoralls-click-button-issue

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you had a wrong div placed after the buttons div there ,,, that was probably the reason ... check again and let me know if sth goes wrong

        let arrows = document.querySelectorAll('.buttons .fas')
        for (const arrow of arrows) {
            arrow.addEventListener('click',function(){
                if (arrow.classList.contains('fa-arrow-up')) {  
            console.log('arrow clicked')
                }
        })
        }
  .buttons {
            font-size: 48px;
        }
    <h1>Dance Time</h1>    
    <div class="buttons">
    <i class="fas fa-arrow-up">first</i>
    <i class="fas fa-arrow-down">second</i>
    <i class="fas fa-arrow-left">third</i>
    <i class="fas fa-arrow-right">fourth</i>
    </div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...