简体   繁体   中英

How to add a class to all similar elements with an index less than the clicked element with jquery?

I have 8 elements in sequence that each represent a yoga pose. When one of these elements is clicked I want to add/remove classes for all the pose cards that come before and after the clicked element. So far I have been able to get the index of the clicked element using the following:

$(".pose-card").click(function () {
    clickedPoseIndex = $(".pose-card").index(this);
});

And then I tried to use a filter function to get the ones whose index is less than the clicked one with something like this:

let prevPoses = $(".pose-card").filter(function () {
        return parseInt($(".pose-card").index(this) < clickedPoseIndex);
    });

But that did not work. Please let me know if you can think of any better solutions. Much appreciated!

What you want to do inside filter is get the index as int (hence the parseInt function) and compare with the value you've stored in clickedPoseIndex which is already an int. You've simply missed a bracket or misplaced one. All you have to do is:

let prevPoses = $(".pose-card").filter(function () {
    return parseInt($(".pose-card").index(this)) < clickedPoseIndex;
});

Edit

Don't need to use parseInt either as the value returned is already an int so:

return $(".pose-card").index(this) < clickedPoseIndex;

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