jQuery 页面加载时RemoveClass AddClass

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28570852/
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-26 16:29:03  来源:igfitidea点击:

RemoveClass AddClass When Page Load

jqueryhtmlcss

提问by abcid d

I have several <div>tags with different class names. When the page loads, I want to remove and add another class in a certain <div>, but somehow it doesn't work as expected.

我有几个<div>具有不同类名的标签。当页面加载时,我想在某个 中删除并添加另一个类<div>,但不知何故它没有按预期工作。

LIVE CODE

实时代码

HTML

HTML

<div class="redBG">
    <div class="yellowIcon"></div>
</div>   
<div class="greenBG">
    <div class="yellowIcon"></div>
</div> 

CSS

CSS

.redBG{
    background-color:red;
    width: 300px;
    height:30px;
    z-index: 1;
}
.yellowIcon{
    background-color:yellow;
    width: 20px;
    height:20px;
    cursor: pointer;
    z-index:20;
}
.greenBG{background-color:green}

.black{background-color:black}

JS

JS

$('div, .redBG').load(
    function()
    {
        $(this).removeClass('.redBG').addClass('.black');
    }
);

回答by Darren

In jQuery, .load is for loading data from a server and inserting it into an element: http://api.jquery.com/load/

在 jQuery 中,.load 用于从服务器加载数据并将其插入到元素中:http: //api.jquery.com/load/

Here's jQuery for the page load and changing the classes:

这是用于页面加载和更改类的 jQuery:

$(document).ready(function() {
  $('.redBG').removeClass('redBG').addClass('black');
});

Also, don't use a period for the class when using removeClass and addClass.

此外,在使用 removeClass 和 addClass 时,不要为类使用句点。

JSFiddle: http://jsfiddle.net/15jg5hbn/

JSFiddle:http: //jsfiddle.net/15jg5hbn/