如何使用jQuery检查元素是否包含类?

2021年5月16日17:11:00 发表评论 1,353 次浏览

方法1:使用hasClass()方法:hasClass()是jQuery中的内置方法, 用于检查具有指定类名的元素是否存在。它返回一个布尔值, 指定该类是否存在于元素中。这可用于检查多个类。

语法如下:

$('element').hasClass('className')

例子:

<!DOCTYPE html>
<html>
      
<head>
     <title>
         How to check an element contains
         a class using jQuery?
     </title>
      
     <script src =
         "https://code.jquery.com/jquery-3.3.1.min.js">
     </script>
</head>
  
<body>
     <h1 style = "color: green">
         lsbin
     </h1>
      
     <b>
         How to check an element contains
         a class using jQuery?
     </b>
  
     <p class = "example-class">
         This element has "example-class".
     </p>
  
     <p>Does the element have class?
         <span class = "output"></span>
     </p>
  
     <button onclick = "checkForClass()">
         Click to check
     </button>
      
     <!-- Script to use hasClass() method to
         check the existence of class name -->
     <script type = "text/javascript">
         function checkForClass() {
             classCheck = $('p').is('.example-class');
             document.querySelector('.output').textContent
                     = classCheck;
         }
     </script>
</body>
  
</html>

输出如下:

检查类有类

方法2:使用is()方法:这类似于以上方法, 并且可以根据需要用于检查更多属性。选择必需元素, 然后像CSS类选择器一样传递类名。它返回一个布尔值, 指定该类是否存在于元素中。这可用于检查多个类。

语法如下:

$('element').is('.className')

例子:

<!DOCTYPE html>
<html>
      
<head>
     <title>
         How to check an element contains
         a class using jQuery?
     </title>
      
     <script src =
         "https://code.jquery.com/jquery-3.3.1.min.js">
     </script>
</head>
  
<body>
     <h1 style = "color: green">
         lsbin
     </h1>
      
     <b>
         How to check an element contains
         a class using jQuery?
     </b>
  
     <p class = "example-class">
         This element has "example-class".
     </p>
  
     <p>Does the element have class? 
         <span class = "output"></span>
     </p>
  
     <button onclick = "checkForClass()">
         Click to check
     </button>
      
     <!-- Script to use is() method to
         check the existence of class name -->
     <script type = "text/javascript">
         function checkForClass() {
             classCheck = $('p').is('.example-class');
             document.querySelector('.output').textContent
                     = classCheck;
         }
     </script>
</body>
  
</html>

输出如下:

检查类是

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: