Javascript 在页面加载时向对象添加类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4995440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:08:02  来源:igfitidea点击:

Add Class to Object on Page Load

javascriptonload

提问by Miles Pfefferle

Basically I want to make this:

基本上我想做这个:

<li id="about"><a href="#">About</a>

Into this when the page loads:

当页面加载时进入:

<li id="about" class="expand"><a href="#">About</a>

I found this thread, but am not so good with javascript and couldn't adapt it: Javascript: Onload if checkbox is checked, change li class

我找到了这个线程,但对 javascript 不太好,无法适应它: Javascript: Onload if checkbox is check, change li class

回答by Jacob Relkin

This should work:

这应该有效:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

或者,如果您使用的是 jQuery:

$(function() {
  $('#about').addClass('expand');
});

回答by Swaff

I would recommend using jQuerywith this function:

我建议将jQuery与此功能一起使用:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

这将在 dom 准备好页面加载时将 expand 类添加到 id 为 about 的元素中。