[英]Everything within if else being executed when it shouldn't
I have the following if else statement:我有以下 if else 语句:
let userIconText = document.getElementsByClassName("iconText");
let userIconDiv = document.getElementById("userIcons");
let rCorners2 = document.getElementById("rcorners2");
let homeContainerDiv = document.getElementById("homePanel");
let icons = document.querySelectorAll('#userIcons li');
document.getElementById("menuFilter").onclick = function(){
for (let i = 0; i < userIconText.length; i++) {
for (let j = 0; j < icons.length; j++) {
if (userIconText[i].style.display !== 'block') {
userIconText[i].style.display = "block";
console.log("1");
userIconDiv.setAttribute("style","width:10vw");
icons[i].setAttribute("style","margin:75px 20px 0 10px");
console.log("2");
homeContainerDiv.setAttribute("style","width:85vw; transform: translateX(5%);");
rCorners2.setAttribute("style","width: 53vw; left: 295px");
console.log("3");
} else {
userIconText[i].style.display = "none";
console.log("4");
userIconDiv.setAttribute("style","width:5vw");
homeContainerDiv.setAttribute("style","width:90vw");
console.log("5");
icons[i].removeAttribute("style", "margin");
rCorners2.removeAttribute("style", "width");
console.log("6");
}
}
}
}
Now this was working but now for some reason everything in this statement is being executed, hence why I have the console log of the numbers to test this, when I do click on the "menuFilter" I check the console log and it shows the numbers 1 through to 6. I just don't get why this is now happening, it worked yesterday and now I'm having this issue.现在这是可行的,但是由于某种原因,现在该语句中的所有内容都在执行,因此为什么我有数字的控制台日志来测试它,当我单击“menuFilter”时,我检查了控制台日志并显示了数字从 1 到 6。我只是不明白为什么现在会发生这种情况,它昨天有效,现在我遇到了这个问题。 So really when I first click on "menuFilter" it shoukd only be everything before the else getting executed and then when I click it again, it should be everything after the else.
所以真的,当我第一次点击“menuFilter”时,它应该只是 else 执行之前的所有内容,然后当我再次点击它时,它应该是 else 之后的所有内容。 Any advice on how to sort this would be greatly appreciated
任何关于如何排序的建议将不胜感激
The if-else is inside of two for loops. if-else 在两个 for 循环中。
On different repetitions, it may trigger different if branches.在不同的重复上,它可能会触发不同的 if 分支。
That's what I can tell based on the code you posted.这就是我可以根据您发布的代码判断的内容。
Figured out the issue, thanks for the help.解决了问题,感谢帮助。 For the userIconText there are 7 elements and due to a change being made, in the icons there are 8 elements, so it seems that due to that, it was running an extra repetition than it should have been which was causing it running the parts after the else condition as well.
对于 userIconText 有 7 个元素,并且由于进行了更改,在图标中有 8 个元素,所以似乎正因为如此,它运行的重复次数超出了它应该运行的次数,这导致它运行了之后的部件else 条件也是如此。
So what I've done is add the following to the second for loop:所以我所做的是将以下内容添加到第二个 for 循环中:
for (let j = 0; j < icons.length; j++) {
if(icons[j].classList.contains("hidden-search")) {
continue;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.