简体   繁体   中英

jquery loop click event doesn't work with eq(i)

I'm trying to add click event to 6 buttons which gonna toggle slide 6 different contents (in order). So basically I click on button 1 and the content 1 will slide up/down etc. I created code below which works but I don not know how to loop it to makes it simpler and works.

WORKING CODE WITHOUT LOOP:

var dropdownButtons = $('div[class*="_dropdown_but"]');
var dropdownContents = $('div[class*="_dropdown_content"]');


dropdownButtons.eq(0).click(function() {
    dropdownContents.eq(0).slideToggle();
});

dropdownButtons.eq(1).click(function() {
    dropdownContents.eq(1).slideToggle();
});

dropdownButtons.eq(2).click(function() {
    dropdownContents.eq(2).slideToggle();
});

dropdownButtons.eq(3).click(function() {
    dropdownContents.eq(3).slideToggle();
});

dropdownButtons.eq(4).click(function() {
    dropdownContents.eq(4).slideToggle();
});

dropdownButtons.eq(5).click(function() {
    dropdownContents.eq(5).slideToggle();
});

I tried to use FOR loop but it doesn't work and non error shows up.

NOT WORKING LOOP I CREATED:

for (i = 0; i < dropdownButtons.length; i++) {
        dropdownButtons.eq(i).click(function() {
        dropdownContents.eq(i).slideToggle();
    });
}

I've tried to write "eq(i)" in a different way like "eq( + i + )" or "eq( + 'i' + )" or "eq(' + i + ')" but nothing changed.

When you declare a variable in JavaScript, the variables are scoped to function they are created in or if they are in outside of function , they exist in the global scope.

When you create a function , the function inherits the variables from the parent scope.

When you create a function inside of a for loop, the function will inherit the i from the parent scope and by the time you click on any of the dropdown buttons, i would have incremented to dropdownButtons.length .

To counter this problem with i , you should add let before declaring i which would make i scoped to the for block instead of global scope. Any function that inherits i will have a copy of i instead of the original i . Read more about let here.

for (let i = 0; i < dropdownButtons.length; i++) {
    dropdownButtons.eq(i).click(function() {
        dropdownContents.eq(i).slideToggle();
    });
}

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