【问题标题】:Want to set a class for each element if certain conditions are true如果某些条件为真,想为每个元素设置一个类
【发布时间】:2013-08-06 14:23:18
【问题描述】:

如果某些条件为真,我正在尝试为每个语句中的元素添加不同的类。代码如下:

$('.horizontal').each(function() {              
            if($(this).children().size() == 3){
                console.log('the number 3')
                $('.horizontal > div').addClass('span4');
            }
            if($(this).children().size() == 6){
                console.log('the number 6')
                $('.horizontal > div').addClass('span2');
            }
        });

问题是我使用最后一个 if 语句设置所有内容,而不是根据输出独立分配一个类。所以,如果我有一个元素有 3 个子元素,然后一个元素有 6 个子元素,它们都会应用“span2”。任何帮助表示赞赏。

【问题讨论】:

    标签: jquery if-statement each


    【解决方案1】:

    您的选择器$('.horizontal > div') 会选择具有“水平”类的元素内的所有 div,而不仅仅是具有 6 个子元素的元素。在这两个上,你可能想要$(this).children('div').addClass('spanWhatever');

    【讨论】:

      【解决方案2】:

      为什么不:

      $('.horizontal').children().addClass(function(){
          switch ( $(this).parent().children().length ) {
              case 3:
                  return 'span4';
                  break;
              case 6:
                  return 'span2';
                  break;
          }
      });
      

      JS Fiddle proof-of-concept.

      或者,迭代父母,而不是所有孩子(诚然,这是一个昂贵的解决方案):

      $('.horizontal').each(function(){
          var self = $(this),
              newClass;
          switch (self.children().length) {
              case 6:
                  newClass = 'span2';
                  break;
              case 3:
                  newClass = 'span4';
                  break;
              default:
                  newClass = '';
                  break;
          }
          self.children().addClass(newClass);
      });
      

      JS Fiddle proof-of-concept.

      甚至:

      var classes = {
          '3' : 'span4',
          '6' : 'span2'
      };
      
      $('.horizontal').each(function(){
          var self = $(this),
              kids = self.children();
          kids.addClass(classes[kids.length] || '');
      });
      

      JS Fiddle proof-of-concept.

      参考资料:

      【讨论】:

      • 因为您要为每个孩子而不是每个父母调用此函数,可能需要 3 或 6 次调用而不是 1 次。通常有很多冗余。
      • @Logan:同意,这不必要的昂贵。
      猜你喜欢
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 2016-09-17
      • 2021-12-16
      • 2016-08-28
      • 1970-01-01
      相关资源
      最近更新 更多