两种修改方法:1、用attr()修改class属性的值,语法“dom元素对象.attr("class","新类名")”;2、移除旧类后添加新类,语法“dom元素对象.removeClass("旧类名").addClass("新类名")”。

本教程操作环境:windows7系统、jquery1.10.2版本、Dell G3电脑。
jquery修改dom元素class名的方法
方法1:直接使用attr()修改class属性的值
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","intro2");
});
});
</script>
<style type="text/css">
.intro1 {
font-size: 120%;
color: red;
}
.intro2 {
font-size: 120%;
color: green;
}
</style>
</head>
<body>
<h1>这是一个段落标题</h1>
<p class="intro1">这是一个段落</p>
<p> 这是另外一个段落</p>
<button>修改p元素的 "intro1" 类</button>
</body>
</html>
方法2:使用removeClass()和addClass()
先使用removeClass()移除指定类
再使用addClass()添加新类
<!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").removeClass("intro1").addClass("intro2");
});
});
</script>
<style type="text/css">
.intro1 {
font-size: 120%;
color: red;
}
.intro2 {
font-size: 120%;
color: green;
}
</style>
</head>
<body>
<h1>这是一个段落标题</h1>
<p class="intro1">这是一个段落</p>
<p> 这是另外一个段落</p>
<button>修改p元素的 "intro1" 类</button>
</body>
</html>
【推荐学习:jQuery视频教程、web前端视频】
以上就是jquery怎么修改dom元素的class名的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号