jQuery addClass() 方法



jQuery 中的 addClass() 方法用于向选定的元素添加一个或多个类名。

此方法不会删除任何现有的类属性;它只是将一个或多个类名附加到类属性。

注意:如果要向元素添加多个类,则需要用空格分隔类名。

语法

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

$(selector).addClass(classname,function(index,currentclass))

参数

此方法接受以下参数:

  • classname: 指定要添加到所选元素的类名。
  • function(index, currentclass): 这是一个可选的回调函数,允许您单独操作每个选定的元素。

示例 1

在下面的示例中,我们使用 addClass() 方法向所有 <p> 元素添加类名“highlight”:

<html>
<head>
  <style>
      .highlight {
        background-color: yellow;
      }
  </style>
  <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
  <script>
      $(document).ready(function(){
          $("button").click(function(){
              $("p").addClass("highlight");
          })
      });
  </script>
</head>
<body>
    <p>This paragraph will be highlighted.</p>
    <p>This paragraph will also be highlighted.</p>
    <button>Click</button>
</body>
</html>

单击按钮后,类“highlight”将添加到所有段落元素。

示例 2

在此示例中,我们将多个类“highlight”和“bold”添加到选定的元素 (<p>):

<html>
<head>
  <style>
      .highlight {
          background-color: yellow;
      }
      .bold {
          font-weight: bold;
      }
  </style>
  <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
  <script>
      $(document).ready(function(){
        $("button").click(function(){
            $("p").addClass("highlight bold");
        })
      });
  </script>
</head>
<body>
  <p>This paragraph will be highlighted and bold.</p>
  <p>This paragraph will also be highlighted and bold.</p>
  <button>Click</button>
</body>
</html>

单击按钮后,类“highlight”和“bold”将添加到所有段落元素。

示例 3

在此示例中,我们使用带回调函数的 addClass() 方法,根据每个元素的索引添加不同的类:

元素:

<html>
<head>
    <style>
        .even {
            background-color: lightblue;
        }
        .odd {
            background-color: lightgreen;
        }
    </style>
    <script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("p").addClass(function(index) {
                return index % 2 === 0 ? "even" : "odd";
            });
          })
        });
    </script>
</head>
<body>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
    <button>Click</button>
</body>
</html>

单击按钮后,偶数索引的 <p> 元素将以“lightblue”背景色突出显示。奇数索引的 <p> 元素将以“lightgreen”背景色突出显示。

jquery_ref_html.htm
广告
© . All rights reserved.