简体   繁体   English

用jQuery更改前一个元素的子类的类

[英]Change class of previous element's child with jquery

I'm trying to do a toggle on click that changes a class (font awesome) like so: 我正在尝试在单击上进行切换,以更改类(真棒),如下所示:

$( ".expandTrigger" ).click(function() {
    $( ".expand" ).first().toggle( "fast", function() {});

    if ( $( this ).prev().child().is( ".fa-plus-circle" ) ) {
      $('.fa-plus-circle').toggleClass('.fa-minus-circle')
    }

    if ( $( this ).prev().child().is( ".fa-minus-circle" ) ) {
      $('.fa-minus-circle').toggleClass('.fa-plus-circle')
    }
  });

});

What am I doing wrong? 我究竟做错了什么? I've run through several examples on SO, but not found anything that can help on this situation. 我在SO上浏览了几个示例,但没有找到任何可以帮助解决这种情况的示例。 HTML is as follows: HTML如下:

<a href="#"  class="expandTrigger open" ><i class="fa fa-minus-circle"></i> Some Title Here</a>
              <div class="expand open" >
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean euismod bibendum laoreet. Proin gravida dolor sit amet lacus accumsan et viverra justo commodo. Proin sodales pulvinar tempor.</p>
                <ul>
                  <li>Cum sociis natoque penatibus et magnis</li>
                  <li>Dis parturient montes, nascetur ridiculus mus</li>
                  <li>Nam fermentum, nulla luctus pharetra</li>
                  <li>Vulputate, felis tellus mollis orci</li>
                  <li>Sed rhoncus sapien nunc eget odio</li>
                </ul>
              </div>

With this html repeated below several times (in order to have several toggle sections). 在下面重复此html几次(以具有多个切换部分)。

The i element is a child of the expandTrigger element, not its siblings child i元素是expandTrigger元素的子元素,而不是其兄弟姐妹的子元素

$(".expandTrigger").click(function () {
    $(this).next(".expand").toggle("fast", function () {});
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle')
});

If you want to change the class after the toggle is complete then 如果要在切换完成后更改班级,则

$(".expandTrigger").click(function () {
    $(this).next('.expand').toggle("fast", function () {
        $(this).prev().find('i').toggleClass('fa-plus-circle fa-minus-circle')
    });
});

Demo: Fiddle 演示: 小提琴

If this block of HTML is repeated, your sequence of elements is A DIV A DIV A DIV ... So to get to the previous plus or minus circle, you have to use .prev() twice: 如果重复HTML的这个块,你的元素的顺序是A DIV一个div一个div ......所以去前面plusminus一圈,你必须使用.prev()两次:

$(this).prev().prev().child().toggleClass('fa-plus-circle fa-minus-circle');

Another problem with your code is that even if you were traversing correctly in your if , you were changing the class of all elements with that class, not just the one you found. 代码的另一个问题是,即使您在if正确遍历,也要使用该类更改所有元素的类,而不仅仅是找到的元素。

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

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