【问题标题】:Selecting certain groups of elements选择某些元素组
【发布时间】:2013-02-08 04:36:20
【问题描述】:

我的网页中有一些分组的<li>标签,如下所示。

<ul id="dg">
   <!-- group-1 -->
   <li data-group="one">....</li>
   <li data-group="one">....</li>
   <li data-group="one">....</li>
   <li data-group="one">....</li>

   <!-- group-2 -->
   <li data-group="two">....</li>
   <li data-group="two">....</li>

   <!-- group-3 -->
   <li data-group="three">....</li>

   <!-- group-4 -->
   <li data-group="four">....</li>
   <li data-group="four">....</li>
   <li data-group="four">....</li>
</ul>

同样,我有大约 20 个(其动态的)&lt;li&gt; 标签组,它们使用“数据组”进行分类。每个类别都有不同数量的&lt;li&gt; 标签。

我想要做的是,我想选择每 4 个组(数据组)并使用 jQuery 将一个名为“edge”的 CSS 类添加到其所有 &lt;li&gt; 标记或使用 nth 添加一个 CSS 属性。

请帮我解决这个问题。

感谢和问候

【问题讨论】:

  • 你的意思是:每组4里?还是每个 li 都带有 data-group="four"?还是第 1 组、第 5 组、第 9 组、...?
  • 我想选择每 4 个数据组,例如
  • 等等……
  • 组名和你在问题中写的一样,直到“二十”?
  • 动态,可以任意
  • 标签: jquery html css css-selectors


    【解决方案1】:

    更新

    您不能简单地使用选择器。您必须遍历所有 li 并推断它们是否属于您想要的组

    var currentGroup = ""; //Name of the group currently checked 
    var counter = 0; //Number of group found
    
    //Loop through the items
    $('#dg li').each(function(){
        //Check if we are checking a new group
        if(currentGroup != $(this).attr('data-group'))
        {
            //If yes, save the name of the new group
            currentGroup = $(this).attr('data-group');
            //And increment the number of group found
            counter++;
        }
    
        //If the number of the group is a multiple of 4, add the class you want
        if((counter % 4) == 0)
            $(this).addClass('edge');
    });
    

    【讨论】:

    • 爱你,我的朋友.. 非常感谢。这就像一个魅力。如果您能解释一下(代码行后的一些 cmets),我将不胜感激,因为我无法理解。
    • 如果你知道组数的限制,我可能会手动只运行你想要的组,以避免不必要地循环你不想要的项目。
    • 我添加了一些cmets
    【解决方案2】:

    比如:

    $('li[data-group="four"]').each(function(){
        $(this).addClass('edge');
    });
    

    你是这个意思吗?

    更像是:

    function processItems(items){
        items.each(function(){
            $(this).addClass('edge');
        });
    }
    processItems($('li[data-group="four"]'));
    processItems($('li[data-group="eight"]'));
    processItems($('li[data-group="twelve"]'));
    

    我不知道性能提升或做类似的事情,但循环遍历每个 li 项目可能会很糟糕而且很慢,具体取决于列表中它们的数量。不是说我在这里是最好的方法,但是如果你有数百个 li 项目,你的循环可能会运行得很慢。

    【讨论】:

    • 与此类似,但我需要每第 4 组选择一次。大约有 20 个组,所以我需要选择 4、8、12、16 等等....
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签