遍历具有类名的项目并将其隐藏

时间:2019-06-20 11:25:35

标签: javascript html for-loop

所以我很确定我的循环是正确的,但是它似乎只隐藏第一个元素,而将其余元素留在后面(它仍然可以很好地输出结果...)

var Sender = document.getElementsByClassName("portlet-section-body caf-primary-row")
var Senders = Sender.length;


//console.log(Sender[0].cells[3].innerHTML)

var excludedSenders = ["REKONDIS SE (Rekondis Sweden)", "SE_201024_LRF_Media (LRF Media)", "SE_201461_Dustin (Dustin)"]
console.log("Senders " + Sender.length);
console.log("excludedSenders " + excludedSenders.length);


for (var i = 0; i < Senders; i++){
console.log(Sender[i]);
    for (var j = 0; j < excludedSenders.length; j++){
        if (Sender[i].cells[3].innerHTML.indexOf(excludedSenders[j]) != -1){
            Sender[i].hide()
        }
    }
}

项目 enter image description here

运行javascript后的项目 enter image description here

它怎么会找到所有物品,却只隐藏1个?

3 个答案:

答案 0 :(得分:0)

好吧,这是因为您正在隐藏元素,然后尝试访问其他单元格

var Sender = document.getElementsByClassName("portlet-section-body caf-primary-row")
var Senders = Sender.length;

var excludedSenders = ["REKONDIS SE (Rekondis Sweden)", "SE_201024_LRF_Media (LRF Media)", "SE_201461_Dustin (Dustin)"]
var excludedSendersLength = excludedSenders.length;

for (let i = 0; i < Senders; i++){
    for (let j = 0; j < excludedSenders; j++){
        if (Sender[i].cells[3].innerHTML.indexOf(excludedSenders[j]) != -1) {
            Sender[i].hide()
            break;
        }
    }
}

答案 1 :(得分:0)

尝试一下:

const Sender          = document.getElementsByClassName("portlet-section-body caf-primary-row")
,     excludedSenders = [ "REKONDIS SE (Rekondis Sweden)"
                        , "SE_201024_LRF_Media (LRF Media)"
                        , "SE_201461_Dustin (Dustin)"
                        ]
;

for (let e_Sender of Sender)
{
  console.log(e_Sender.cells[3].textContent);

  for (let ex_Sender of excludedSenders)
  {
    if (e_Sender.cells[3].textContent.indexOf(ex_Sender) > -1)
    {
      e_Sender.hide()
      break
    }
  }
}

答案 2 :(得分:0)

发现了问题!

有2个班级。

portlet-section-body caf-primary-row
portlet-section-alternate caf-primary-row

解释了为什么它不起作用的原因,真的很奇怪,它使用了2种不同的类。 我要感谢大家的帮助和您的时间。