代码之家  ›  专栏  ›  技术社区  ›  Roberto

JQuery-如果元素有类,则添加类

  •  3
  • Roberto  · 技术社区  · 8 年前

    我想将类添加到具有类“alignleft”的元素中。我的代码:

    $(document).ready(function () {
        if($('.foto').children().hasClass('alignleft')){
            $(this).addClass('animated bounceInLeft');
        }
    });
    

    它不起作用,我也不知道为什么。但是如果我使用 $('.foto').children().addClass('animated bounceInLeft'); 它将类应用于所有具有类alignleft的子元素。所以问题出在 $(this) 大概

    3 回复  |  直到 8 年前
        1
  •  1
  •   Pranav C Balan Ansh Takalkar    8 年前

    你不能用 this ,它引用窗口对象。而是将类用作中的选择器 children() 方法

    $('.foto').children('.alignleft').addClass('animated bounceInLeft');
    

    或者使用 child selector( > )

    $('.foto > .alignleft').addClass('animated bounceInLeft');
    
        2
  •  1
  •   Milind Anantwar    8 年前

    可以使用类选择器将元素作为目标,然后向其添加类:

    $('.foto .alignleft').addClass('animated bounceInLeft');
    
        3
  •  0
  •   zakhefron    8 年前

    尝试

    $(document).ready(function() {
     var elem = $('.foto .alignleft');
      if (elem) {
        elem.addClass('animated bounceInLeft');
      }
    });
    

    $(document).ready(function() {
       $('.foto .alignleft').addClass('animated bounceInLeft');
    });
    

    $(document).ready(function() {
     var elem = $('.foto .alignleft');
      if (elem) {
        elem.addClass('animated bounceInLeft');
      }
    });
    .alignleft{color:red;}
    .alignright{color:green;}
    
    .animated{background:lightgrey;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="foto">
      <div class="alignleft">
        Div A
      </div>
      
      <div class="alignleft">
        Div B
      </div>
      
      <div class="alignright">
        Div C
      </div>
       <div class="alignright">
        Div D
      </div>
    </div>