【问题标题】:Hide 1st, 3rd, 4th, 6th, 7th, 9th, 10th, 12th div container隐藏第 1、第 3、第 4、第 6、第 7、第 9、第 10、第 12 个 div 容器
【发布时间】:2017-06-28 18:17:32
【问题描述】:

我有以下数组,它们是 html 页面中的元素:

["1", "1", "1","2", "2", "2","3", "3", "3","4", "4", "4",];

更具体地说,这些是 div:

<div class="abc1">1</div>
<div class="abc2">1</div>
<div class="abc3">1</div>
<div class="abc4">2</div>
<div class="abc5">2</div>
<div class="abc6">2</div>
<div class="abc7">3</div>
<div class="abc8">3</div>
<div class="abc9">3</div>
<div class="abc10">4</div>
<div class="abc11">4</div>
<div class="abc12">4</div>

我想隐藏第 1、3、4、6、7、9、10、12 格。

我试过这段代码,但它只隐藏了每个奇数。

$(document).ready(hideLabelFF);

function hideLabelFF(){
$('*[class^="abc"]').each(function (i){
    $('*[class^="abc"]:nth-of-type(2n+1)').hide();
});
};

【问题讨论】:

  • 你不需要javascript,你的div已经分配了特定的类,你为什么不使用它呢?
  • 你不能试试css吗? div:nth-child(1),div:nth-child(3),div:nth-child(4) { 可见性:隐藏; } 所以,开始?
  • $('.abc1, .abc3, .abc4, .abc6, .abc7, .abc9, .abc10, .abc12').hide();

标签: javascript jquery html


【解决方案1】:

使用 2n+1,您将定位到 奇数 div。你有 2 个系列,一个是 1,4,7,10...,另一个是 3,6,9,12...

只需尝试关注

function hideLabelFF(){
    $('*[class^="abc"]:nth-of-type(3n+1)').hide();
    $('*[class^="abc"]:nth-of-type(3n)').hide();
}

供参考 - plunker

【讨论】:

    【解决方案2】:

    我不确定此操作的目的是什么;听起来像是一项家庭作业,要找到最聪明的方法。

    最直接的方法是:

    [1, 3, 4, 6, 7, 9, 10, 12].forEach(num => $(`.abc${num}`).hide());
    

    但这并不聪明。你已经注意到那里的模式。所示元素为 2、5、8、11,即 3n-1。因此,您可以这样做:

    $('*[class^="abc"]:nth-of-type(3n-2)').hide();
    $('*[class^="abc"]:nth-of-type(3n)').hide();
    

    反转隐藏:

    $('*[class^="abc"]').hide();
    $('*[class^="abc"]:nth-of-type(3n-1)').show();
    

    或者最后,使用.not() 方法将这一切集中到一个单行中:

    $('*[class^="abc"]').not(":nth-of-type(3n-1)").hide();
    

    【讨论】:

    • 很高兴您回答了所有可能的解决方案!
    • 我很确定它们还不是所有解决方案;)
    猜你喜欢
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2014-01-04
    • 2021-05-31
    • 1970-01-01
    • 2014-04-02
    相关资源
    最近更新 更多