简体   繁体   English

为什么我不能用 javascript 删除这个 class?

[英]Why can't I remove this class with javascript?

I'm trying to make a skeleton loading screen by having a class 'skeleton' on the elements which styles them then removing it with javascript after a timeout.我正在尝试通过在 styles 元素上设置 class “骨架”然后在超时后使用 javascript 将其删除来制作骨架加载屏幕。 The issue is that i can't get the javascript to work.问题是我无法让 javascript 工作。

Here's my javascript to remove the class, why isn't it working?这是我的 javascript 删除 class,为什么它不起作用?

const timeout = setTimeout(loading, 3000);

function loading() {
    const element = document.getElementById("skeleton");
    element.classList.remove("skeleton");   
  }

What I think is happening is that you have too many "skeleton" elements with the same id, and ids have to be unique.我认为正在发生的事情是您有太多具有相同 ID 的“骨架”元素,并且 ID 必须是唯一的。 So remove the ids, and target the classes instead, and use forEach to iterate over each of them to remove the class.因此,删除 id,改为以类为目标,并使用forEach遍历每个类以删除 class。

 const timeout = setTimeout(loading, 3000); function loading() { const skeletons = document.querySelectorAll('.skeleton'); skeletons.forEach(skeleton => { skeleton.classList.remove('skeleton'); }); }
 .skeleton { color: red; }
 <div class="skeleton">One</div> <div class="skeleton">Two</div> <div class="skeleton">Three</div> <div class="skeleton">Four</div>

You are calling getElmentById on Class. Can You Share The HTML Elment whose id or class is skeleton try this您正在 Class 上调用 getElmentById。您可以分享 ID 或 class 为骨架的 HTML Elment 试试这个


function loading() {
    const element = document.getElementsByClassName("skeleton")[0];
    element.classList.remove("skeleton");   
  }

I think the reason behind its not working is that your trying to remove the skeleton class from the skeleton itself.我认为它不起作用的原因是您试图从骨架本身移除骨架 class。 Try targeting the parent Element of the skeleton and then remove the skeleton from the parent Element.尝试以骨架的父元素为目标,然后从父元素中移除骨架。 Did you try using:您是否尝试使用:

const parentNode=document.querySelector(".parentElem");
parentNode.removeChild(document.querySelector(".skeleton"));

Did you notice you are trying to get an element by using getElementById whereas you stated skeleton is a class.您是否注意到您正在尝试使用getElementById获取元素,而您声明的skeleton是 class。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM