简体   繁体   中英

my javascript queryselectorall does not capture the second class name as intended

I have two images with different classes but I want the same JavaScript to be applied to both. This javascript basically allows for a slideshow by clicking on the button, but this only works for the images with the mySlides class, not the albums class. Take a look:

 var slideIndex = 1; showDivs(slideIndex); function plusDivs(n) { showDivs(slideIndex += n); } function showDivs(n) { var i; var x = document.querySelectorAll(".mySlides, .albums"); if (n > x.length) { slideIndex = 1 } if (n < 1) { slideIndex = x.length }; for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } x[slideIndex - 1].style.display = "block"; }
 <link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/> <div class="inner"> <img class="mySlides" src="./imgs/IMG_1552.JPG"> <img class="mySlides" src="./imgs/IMG_0915.jpg"> <button class="w3-button w3-display-left" onclick="plusDivs(-1)">&#10094;</button> <button class="w3-button w3-display-right" onclick="plusDivs(+1)">&#10095;</button> </div> <div class="inner"> <img class="albums" src="./imgs/travis.jpg"> <img class="albums" src="./imgs/killy.jpg"> <button class="w3-button w3-display-left" onclick="plusDivs(-1)">&#10094;</button> <button class="w3-button w3-display-right" onclick="plusDivs(+1)">&#10095;</button> </div>

The buttons are supposed to move to the next image eg from "travis.jpg" to "killy.jpg" but it only works for the mySlides class and not the albums class

The issue lies in var x = document.querySelectorAll(".mySlides, .albums"); As you have to understand that this query selects all the 4 elements if you want to do for the second element of both classes you would have to go with

var x = document.querySelectorAll(".mySlides");
var y = document.querySelectorAll(" .albums");

and run the further logic on both var seperately

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