我是靠谱客的博主 有魅力向日葵,这篇文章主要介绍jquery怎么修改dom元素的class名,现在分享给大家,希望可以做个参考。

本教程操作环境: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>
登录后复制

1.gif

方法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>
登录后复制

2.gif

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

以上就是jquery怎么修改dom元素的class名的详细内容,更多请关注靠谱客其它相关文章!

最后

以上就是有魅力向日葵最近收集整理的关于jquery怎么修改dom元素的class名的全部内容,更多相关jquery怎么修改dom元素内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(168)

评论列表共有 0 条评论

立即
投稿
返回
顶部