當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JQuery addClass()用法及代碼示例

addClass()方法是一個內置方法jQuery用於向每個選定元素添加更多屬性。它還可用於更改所選元素的屬性。

該方法可以通過兩種不同的方式使用:
1)直接添加類名:在這裏,類名稱可以直接與要選擇的元素一起使用。

用法:

$(selector).addClass(className);

參數:它接受參數“className”,這是要添加的類的名稱。

返回值:它返回帶有添加的新類的選定元素。

示例 1:在此示例中,我們使用above-explained方法。

HTML


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src=
"https://code.jquery.com/jquery-1.10.2.js">
    </script>
    <title>addClass demo</title>
    <style>
        p {
            margin: 8px;
            font-size: 35px;
        }
        .selected {
            display: block;
            border: 2px solid green;
            width: 160px;
            height: 60px;
            background-color: lightgreen;
            padding: 20px;
        }
        .highlight {
            background: yellow;
        }
    </style>
</head>
<body>
    <p>GeeksforGeeks</p>
    <p>gfg</p>
    <p>CSE</p>
    <script>
        $("p").last().addClass("selected");
    </script>
</body>
</html>

在上麵的代碼中,選擇了“p”元素,並且借助以下命令將“selected”類僅應用於最後一個“p”元素.last()方法和.addClass()jQuery 的方法。

輸出:

2)通過傳遞函數來添加新類:在這裏,可以將函數傳遞給所選元素的.addClass()。

用法:

$(selector).addClass(function);

參數:它接受參數“function”。

返回值:它返回具有添加函數的選定元素。

示例 2:以下是 above-explained 方法的示例。

HTML


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src=
"https://code.jquery.com/jquery-1.10.2.js">
    </script>
    <style>
        div {
            background: white;
            margin: 20px;
        }
        .red {
            background: red;
            width: 300px;
            margin: 20px;
        }
        .red.green {
            background: lightgreen;
            margin: 20px;
            border: 2px solid green;
        }
        body {
            border: 2px solid green;
            width: 350px;
            height: 200px;
        }
    </style>
</head>
<body>
    <div>This div should be white</div>
    <div class="red">
        This div will be green because now it
        has the both "green" and "red" classes.
    </div>
    <div>This div should be white</div>
    <script>
        $("div").addClass(function (index, currentClass) {
            let addedClass;
            if (currentClass === "red") {
                addedClass = "green";
                $("p").text("There is one green div");
            }
            return addedClass;
        });
    </script>
</body>
</html>

在上麵的代碼中,選擇了 “div” 元素,並在函數的幫助下,將一個新類添加到所選的 div 元素中。

輸出:



相關用法


注:本文由純淨天空篩選整理自kundankumarjha大神的英文原創作品 jQuery addClass() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。