您好,欢迎访问一九零五行业门户网

jquery怎么改变classname(类名)

3种修改方法:1、利用attr()修改class属性的值即可,语法“元素对象.attr(class,新类名);”。2、利用prop()修改class属性的值即可,语法“元素对象.prop(class,新类名);”。3、利用removeclass()和addclass(),语法“元素对象.removeclass(旧类名).addclass(新类名);”。
本教程操作环境:windows7系统、jquery3.6.1版本、dell g3电脑。
jquery改变classname(类名)的方法
方法1:利用attr()修改
attr()可以设置元素的属性和值
只需要修改class属性的值即可,语法:
$(selector).attr("class","新类名");
示例
<!doctype html><html> <head> <meta charset="utf-8" /> <script src="js/jquery-3.6.1.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("div").attr("class", "box2"); }); }); </script> <style> .box1 { height: 150px; background-color: #afeeee; } .box2 { height: 100px; background-color: red; } </style> </head> <body> <div class="box1"></div> <br> <button>改变classname(类名)</button> </body></html>
方法2:利用prop()修改
attr()可以设置元素的属性和值
只需要修改class属性的值即可,修改语法:
$(selector).prop("属性名","新类名");
示例
<!doctype html><html> <head> <meta charset="utf-8" /> <script src="js/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $("button").click(function() { $("div").prop("class","box1"); }); }); </script> <style> .box1 { height: 150px; background-color: #afeeee; } .box2 { height: 100px; background-color: red; } </style> </head> <body> <div class="box2"></div> <br> <button>改变classname(类名)</button> </body></html>
方法3:利用removeclass()和addclass()修改
使用removeclass()删除旧的class
使用addclass()添加新的class
<!doctype html><html> <head> <meta charset="utf-8" /> <script src="js/jquery-3.6.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function(){ $("p").removeclass("intro1").addclass("intro2"); }); }); </script> <style> .intro1 { font-size: 120%; color: red; } .intro2 { color: peru; background-color: aquamarine; } </style> </head> <body> <p class="intro1">测试段落</p> <button>改变classname(类名)</button> </body></html>
【推荐学习:jquery教程、web前端视频】
以上就是jquery怎么改变classname(类名)的详细内容。
其它类似信息

推荐信息