style.display似乎不起作用

时间:2017-12-18 00:36:34

标签: javascript css

我试图隐藏/显示某些元素,只有当我使用父节点而不是子元素时,它才有效。有人知道为什么会这样吗?

const ulList = document.querySelector('ul');
const studentList = ulList.querySelectorAll('li');

ulList.style.display = 'none'; // (when I do it like this, everything is fine).

studentList.style.display = 'none'; // (but if I do it like these, the error "Uncaught TypeError: Cannot set property 'display' of undefined" appears on the console)

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

querySelectorAll()仅返回第一个匹配的单个元素,但const studentList = document.querySelectorAll('li'); studentList.forEach(function(li){ li.style.display = 'none'; }); 返回列表。您必须在所有列表项上应用样式。 请尝试以下方式:

{{1}}

答案 1 :(得分:0)

我得到你说的......但是为什么当我这样做时(在一个循环中),显示属性为"阻止"没有生效。口译员只是忽略了它:

const ulList = document.querySelector('ul');
const studentList = document.querySelectorAll('li');

ulList.style.display = 'none';

for (let i = 0; i < studentList.length; i += 1) {
    if ((i + 1) >= numPage && i < y) {
        studentList[i].style.display = 'block';
    }
}

不要注意有条件的。它是我的代码的一部分。循环和条件运行以及当0索引处的第一个元素接收到块属性时,就会发生这种情况。

相关问题