jquery给元素增加类的方法:1、使用attr()方法,语法“$(selector).attr(class,类名)”;2、使用addclass()方法,语法“$(selector).addclass(类名)”。
本教程操作环境:windows7系统、jquery1.10.2版本、dell g3电脑。
jquery中给元素增加一个类
1、使用attr()方法
attr() 方法设置或返回被选元素的属性值。
根据该方法不同的参数,其工作方式也有所差异。
<!doctype html><html> <head> <meta charset="utf-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("p:first").attr("class","intro"); }); }); </script> <style> .intro { font-size: 150%; color: red; } </style> </head> <body> <h1>这是一个标题</h1> <p>这是一个段落。</p> <p>这是另一个段落。</p> <button>给第一个p元素添加一个类名</button> </body></html>
2、使用addclass()方法
addclass() 方法向被选元素添加一个或多个类名。
该方法不会移除已存在的 class 属性,仅仅添加一个或多个类名到 class 属性。
提示:如需添加多个类,请使用空格分隔类名。
<!doctype html><html> <head> <meta charset="utf-8"> <script src="js/jquery-1.10.2.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("p:first").addclass("intro"); }); }); </script> <style> .intro { font-size: 150%; color: pink; } </style> </head> <body> <h1>这是一个标题</h1> <p>这是一个段落。</p> <p>这是另一个段落。</p> <button>给第一个p元素添加一个类名</button> </body></html>
【推荐学习:jquery视频教程、web前端】
以上就是jquery中怎么给元素增加一个类的详细内容。