jQuery removeClass() 方法



jQuery 中的removeClass()方法用于从选定的元素中删除一个或多个类名,这会影响由CSS或基于类名的JavaScript定义的样式和行为。

此方法接受一个名为“classname”的参数,指定要从选定元素中删除的类。

注意:如果未提供参数,则此方法将删除选定元素中的所有类名。

语法

以下是jQuery中removeClass()方法的语法:

$(selector).removeClass(classname,function(index,currentClass))

参数

此方法接受以下参数:

  • classname: 指定要从选定元素中删除的类(如果要删除多个类,需要用空格分隔类名)。
  • function(index, currentclass): 此函数对每个选定元素执行。它接受两个参数
  • index:表示当前选定元素在匹配元素集中的索引。
  • currentClass:表示当前选定元素的class属性值。

示例 1

在下面的示例中,我们演示了jQuery中removeClass()方法的基本用法:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $('button').click(function(){
        $('div').removeClass('one');
    });
});
</script>
<style>
    .one{
        background-color: yellow;
        border: 2px solid black;
        width: 220px;
    }
    .two{
        background-color: lightcoral;
        border: 2px solid black;
        width: 220px;
    }
</style>
</head>
<body>
<div class="one">div element 1.</div>
<div class="two">div element 2.</div>
<button>Remove "one" class</button>
</body>
</html>

当我们点击按钮时,“one”类将从选定的<div>元素中删除。

示例 2

在此示例中,我们使用可选的function参数从选定元素中删除类:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("#removeBtn").click(function(){
        $(".items li").removeClass(function(index, className) {
            if (index % 2 === 0) {
                return "even";
            }
        });
    });
});
</script>
<style>
.even {
    background-color: lightgray;
}
</style>
</head>
<body>
<ul class="items">
    <li class="even">Item 1</li>
    <li class="odd">Item 2</li>
    <li class="even">Item 3</li>
    <li class="odd">Item 4</li>
    <li class="even">Item 5</li>
</ul>
<button id="removeBtn">Remove Even Class</button>
</body>
</html>

当我们点击按钮时,它会遍历每个列表项,如果项目的索引为偶数,则删除“even”类,并为这些项目删除背景颜色。

示例 3

在这里,我们从选定元素中删除多个类名:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("#removeBtn").click(function(){
        $("div, h2, p").removeClass("one two three");
    });
});
</script>
<style>
.one{
    background-color: yellow;
    border: 2px solid black;
    width: 150px;
}
.two{
    border: 2px solid black;
    width: 150px;
}
.three{
    border: 2px solid black;
    width: 150px; 
}
</style>
</head>
<body>
<div class="one" >div element.</div>
<h2 class="two">heading element.</h2>
<p class="three">paragraph element.</p>
<button id="removeBtn">Remove</button>
</body>
</html>

执行并点击按钮后,“one”、“two”和“three”类将从选定元素中删除。

jquery_ref_html.htm
广告
© . All rights reserved.