简体   繁体   English

单击多个元素时,jQuery更改图标

[英]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. 如果我有多个带有图标的div,并且我不想在单击时更改该图标,但是在某种程度上,仅替换了我单击的那个图标,同时所有其他图标保持不变。 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. 基于下面的简单代码,每次单击.clickMore图标都会更改,但是如果您单击第二个.clickMore第一个,则实际上所有它们(由于我们不知道切换哪个)都应更改为默认值。

My simple JS 我简单的JS

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

And even more simple HTML 甚至更简单的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. 您还需要将逻辑与i元素一起应用。

$('.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 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM