HOWTO · jQuery

jQuery 獲取類

本教程演示如何在 jQuery 中獲取類名。

本頁內容

本教程演示瞭如何在 jQuery 中獲取類名。

jQuery 獲取類

attr() 方法可以獲取 jQuery 中的類名。除此方法外,hasClass() 方法可用於檢查特定元素是否具有特定類名。

讓我們描述並展示這兩種方法的示例。

attr() 方法用於獲取 HTML 元素屬性的值。我們可以使用 attr() 方法中的類名作為引數來獲取類的名稱。

使用 attr 方法獲取類名的語法如下。

attr('class')

讓我們試試這個方法的一個例子。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery Get Class Name</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
    $(document).ready(function(){
        $("button").click(function(){
            var Name = $("#DELFTSTACK").attr("class");
            alert(Name);
        });
    });
    </script>
</head>
<body>
    <div id="DELFTSTACK" class="Delfstack">Click the button to get the class name for this element.</div>
    <button type="button">Click Here</button>
</body>
</html>

上面的程式碼將提醒給定元素的類名。見輸出:

jQuery 獲取類

讓我們檢查該類是否具有我們從 attr() 方法獲得的名稱。為此,我們可以使用 hasClass() 方法。

參見示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery Get Class Name</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
    $(document).ready(function(){
        $("button").click(function(){
            var Name = $("#DELFTSTACK").attr("class");
            if ($( "#DELFTSTACK" ).hasClass( Name )){
                alert(Name);
            }
        });
    });
    </script>
</head>
<body>
    <div id="DELFTSTACK" class="Delfstack">Click the button to get the class name for this element.</div>
    <button type="button">Click Here</button>
</body>
</html>

上面的程式碼將有類似的輸出,因為 attr 方法將返回正確的類名,而 hasClass 將返回 true。見輸出:

jQuery Has Class