jquery怎么增加类

本教程操作环境:windows7系统、jquery1.10.2版本、Dell G3电脑。

jquery增加类的两种方法

1、使用attr()

attr()可以设置被选元素的属性值,当属性为“class”时增加类。

该种方法用于之前没有类时,新增类。

示例:向第一个 p 元素添加一个类

<!DOCTYPE html> <html>   <head>   <meta charset="UTF-8">   <script src="js/jquery-1.10.2.min.js"></script>   <script type="text/javascript">    $(document).ready(function() {     $("button").click(function() {      $("p:first").attr("class","intro");     });    });   </script>   <style type="text/css">    .intro {     font-size: 120%;     color: red;    }   </style>  </head>   <body>   <h1>This is a heading</h1>   <p>This is a paragraph.</p>   <p>This is another paragraph.</p>   <button>向第一个 p 元素添加一个类</button>  </body> </html>

2.gif

2、使用addClass()

addClass() 方法向被选元素添加一个或多个类。

该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。如需添加多个类,请使用空格分隔类名。

示例:向第二个 p 元素添加一个类

<!DOCTYPE html> <html>   <head>   <meta charset="UTF-8">   <script src="js/jquery-1.10.2.min.js"></script>   <script type="text/javascript">    $(document).ready(function() {     $("button").click(function() {      $("p:nth-child(3)").addClass("intro");     });    });   </script>   <style type="text/css">    .intro {     font-size: 120%;     color: red;    }   </style>  </head>   <body>   <h1>一个大标题</h1>   <p>第一个段落</p>   <p>第二个段落</p>   <p>第三个段落</p>   <button>向第二个 p 元素添加一个类</button>  </body> </html>

3.gif

【推荐学习:jQuery视频教程、web前端视频】

商匡云商
Logo
注册新帐户
对比商品
  • 合计 (0)
对比
0
购物车