简体   繁体   中英

jQuery change icon on click on multiple elements

If i have multiple div's with icon and i wan't to change that icon on click, but in a way, that only the one i clicked is replaced and at the same time all other icons stay the same. I have accordion like and if i click on icon in first accordion and don't use the same click to close it, but instead open second accordion, which closes first accordion, then icon in first accordion doesn't change back to default.

Here's fiddle with all the data

Based on simple code bellow everytime you click on .clickMore icon is changed, but if you click on second .clickMore first one, actually all of them since we don't know which one is toggled, should be changed to default.

My simple JS

$('.clickMore').click(function() {
  $("i", this).toggleClass("fa-info-circle fa-close");
});

And even more simple HTML

<div class="clickMore">
    <i class="fa fa-info-circle"></i>
</div>

<div class="clickMore">
    <i class="fa fa-info-circle"></i>
</div>

<div class="clickMore">
    <i class="fa fa-info-circle"></i>
</div>

You need to apply the logic with i element also.

$('.clickMore').click(function() {
    ...
    //Toggle class for current element's child 
    $("i", this).toggleClass("fa-info-circle fa-close"); 

    //Remove fa-close and remove fa-info-circle from other elements
    $('.clickMore').not(this).find("i").removeClass("fa-close").addClass("fa-info-circle");
});

Fiddle

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