HTML Javascript setTimeout with multiple elements using getE



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

 $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>";

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

您将需要遍历您的集合,然后执行ELEMENT.style.display = 'none';调用。目前,设置它的方式更像是jQuery风格的操作,其中调用.style.display = 'none'适用于集合的每个元素,但是由于您正在执行vanilla JavaScript,因此必须手动执行此操作。

在你的JavaScript中,我会做这样的事情:

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

我做了[ ...collection ]交易,因为 HTMLCollection 没有本机数组方法,因此为了避免使用 for 循环,我将其设置为数组(奇怪的是,它具有 Symbol.iterator 属性,因此很容易转换为数组。

最新更新