简体   繁体   中英

Calling another function from within an event listener's function

I have a number of .nextBtn elements and I've added click listener to each of them. I'm trying to implement a functionality where if the img is clicked, takeToNextPage() is called. For some reason it's not working.

 let nextBtn = document.querySelectorAll('.nextBtn'); for (let i = 0; i < nextBtn.length; i++) { nextBtn[i].addEventListener('click', function(e) { if (e.target.parentElement.classList.contains('.nextBtn')) { takeToNextPage(); } }); } 
 <div class="page1 page"> page 1 <div class="nextBtnContainer"> <div class="nextBtnText">some text</div> <div class="nextBtn" id="1"> <img src="assets/game-15.png" alt="Next"> </div> </div> </div> <div class="page2 page"> page 2 <div class="nextBtnContainer"> <div class="nextBtnText">Play Mind Reader</div> <div class="nextBtn" id="2"> <img src="assets/game-15.png" alt="Next"> </div> </div> </div> 

Note: Please don't suggest adding event listener to img . I don't want to do that. Also, the actual number of .textBtn elements are more than shown. So solution should probably be scalable.

class should not have . in the beginning

let nextBtn = document.querySelectorAll('.nextBtn');
for(let i = 0; i<nextBtn.length; i++){
  nextBtn[i].addEventListener('click', function(e){
    if(e.target.parentElement.classList.contains('nextBtn')){
      takeToNextPage();
    }
  });
}

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