简体   繁体   中英

For loop inside another for loop JavaScript

I have a simple dynamic list which you can add other elements to and I want each time the client clicks on the circle, a class gets assigned to both the paragraph and the circle. I've tried making a for loop inside another for loop and it works, but it adds the class to all the paragraphs not only one.

这是列表的图像

Here's the code I've tried

let circle = document.querySelectorAll(".circle"),
    paragraph = document.querySelectorAll(".paragraph");
for(i=0; i<circle.length; i++){
    circle[i].addEventListener('click', function(){
        for(i=0; i<paragraph.length; i++){
            paragraph[i].classList.add('class')
        }
    })
}

Here's the HTML

<div class="dynamic" draggable="true">
      <div class="circle"></div>
      <p class="paragraph"></p>
</div>

While you could make sure your loop closes over i properly, then add the class to only paragraph[i] instead of to all paragraphs inside the loop:

const circles = document.querySelectorAll(".circle"),
const paragraphs = document.querySelectorAll(".paragraph");
for (let i = 0; i < circles.length; i++) {
    circles[i].addEventListener('click', function () {
        paragraphs[i].classList.add('class');
    });
}

It looks like the paragraphs might be right next to the circles, in which case navigating to the .nextElementSibling of the clicked circle might work and'd be easier without two separate collections to worry about:

const circles = document.querySelectorAll(".circle"),
for (let i = 0; i < circles.length; i++) {
    circles[i].addEventListener('click', function () {
        circles[i].nextElementSibling.classList.add('class');
    });
}

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