【问题标题】:Jquery / CSS – addClass to first:p of multiple div with specified classJquery / CSS – addClass to first:p of multiple div with specified class
【发布时间】:2010-04-18 22:04:22
【问题描述】:

我正在使用(尝试使用)jQuery 将类添加到 every div 的第一段,类为“.djBio” 我的问题是它只是将类添加到第一个div.djBio,而不是该类的 all div。这是代码。我还在使用花哨的字母 jquery 插件将首字下沉添加到第一段(这也仅适用于第一个 div.djBio,不是全部)

jQuery(function( $ ){
    $('.servicesContent p:first, .about-usContent p:first, .djBio p:first').fancyletter().addClass('firstP');
});

非常感谢您的帮助!

【问题讨论】:

    标签: jquery html css


    【解决方案1】:

    您偶然发现了每个人在某些时候都会遇到的问题::first 并不真正意味着您(起初)认为它意味着什么。 :first 将只返回(最多)一个元素。我能想到的解决问题的最佳方法是使用each():

    $(function() {
      $(".servicesContent, .about-usContent, .djBio").each(function() {
        $(this).find("p:first").addClass("...");
      });
    });
    

    【讨论】:

      【解决方案2】:

      您可以像这样重写代码以将类添加到所有第一个 p 标记:

      $('.servicesContent, .about-usContent, .djBio').each(function() {
          $(this).find('p:first').fancyletter().addClass('firstP');
      });
      

      您的代码的问题在于,它仅在具有给定类的元素中找到 p 标记的第一个实例。

      【讨论】:

        【解决方案3】:

        正如您所发现的,:first selector 匹配您应用它的选择器的第一个元素,并且只会返回(最多)一个元素。

        您需要使用:first-child selector,它将匹配作为其父元素的第一个子元素的任何元素。 (注意如果第一个p之前有不同的元素,还是不行)

        【讨论】:

        • 我意识到了;这就是我第二段中括号的意思。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多