使用getElementsByClassName

时间:2019-01-06 20:08:23

标签: javascript php html arrays html5

我有一些PHP代码来回显目录中的文件列表。它工作正常,但随后我需要使用Javascript在5秒后将其隐藏,但是由于某种原因该脚本无法正常工作。你知道我需要修理什么吗?

 $dir = "/var/www/files/";
    $list = preg_grep('/^([^.])/', scandir($dir));
    foreach (preg_grep('/^([^.])/', scandir($dir)) as $list)
    echo "<span class='list' style='color:red'>$list</span>"."<br>";
    echo "<script>
           setTimeout(function () {
           document.getElementsByClassName('list').style.display='none';}, 5000);
           </script>";

1 个答案:

答案 0 :(得分:1)

我认为问题与尝试操纵document.getElementsByClassName的返回值有关。从此方法调用返回的对象是HTMLCollection,它类似于数组,并且绝对不是HTMLElement。

您将要遍历集合,然后进行ELEMENT.style.display = 'none';调用。当前,设置方式更多地是一种jQuery风格的操作,其中调用.style.display = 'none'应用于集合的每个元素,但是由于您使用的是普通JavaScript,因此必须手动执行。

在您的JavaScript中,我将执行以下操作:

const collection = document.getElementsByClassName('list');
[ ...collection ].forEach(element => {
    element.style.display = 'none';
});

我之所以进行[ ...collection ]处理是因为HTMLCollection没有本机数组方法,因此为了避免使用for循环,我将其设为一个数组(奇怪的是,它具有一个{{1} }属性,因此很容易转换为数组。