dongyao4419 2019-01-06 20:08
浏览 84

使用getElementsByClassName的HTML Javascript setTimeout,包含多个元素

I have some php code to echo a list of files in a directory. It works fine, but then I need to use Javascript to hide them after 5 seconds, but for some reason the script doesn't work. Do you know what I need to fix?

 $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条回答 默认 最新

  • douchenhui5569 2019-01-08 18:38
    关注

    I think the problem has to do with trying to manipulate the return value of document.getElementsByClassName. The object returned from this method call is an HTMLCollection, which is array-like and definitely not an HTMLElement.

    You will want to loop over your collection and then do the ELEMENT.style.display = 'none'; call. Currently the way you have it set up is more of a jQuery style operation, where calling .style.display = 'none' applies to each element of the collection, but because you're doing vanilla JavaScript, you have to do it manually.

    In your JavaScript I would do something like this:

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

    I did the [ ...collection ] deal because an HTMLCollection doesn't have native array methods, and so to avoid using a for loop I made it an array (oddly, it has a Symbol.iterator property, so it's easy to convert to an array.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?