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.jquery.com/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.jquery.com/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.jquery.com/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.