0
点赞
收藏
分享

微信扫一扫

用javascript和jQuery实现对标签设置属性

有态度的萌狮子 2022-01-22 阅读 30

第一种方式:用js原生方法

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			div{
				border: 5px solid red;
				width: 100px;
				height: 100px;
			}
			.x{
				background-color: aquamarine;
			}
		</style>
		
		<script type="text/javascript">
			function fun1(){
				var element=window.document.getElementById("d1")
				element.setAttribute("class",x)
				
				
			}
		</script>
	</head>
	<body onload="fun1()">
		<div id="d1"></div>
	</body>
</html>

第二种方式:用jQuery方法

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			div{
				border: 5px solid red;
				width: 100px;
				height: 100px;
			}
			.x{
				background-color: yellow;
			}
		</style>
		
		<script type="text/javascript" src="jquery.min.js"></script>
		<script type="text/javascript">
			function fun1(){
				var element=$("#d1")
				element.addClass("x")
			}
		</script>
	</head>
	<body onload="fun1()">
		<div id="d1"></div>
	</body>
</html>

优化

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			.y{
				border: 5px solid red;
				width: 100px;
				height: 100px;
			}
			.x{
				background-color: yellow;
			}
		</style>
		
		<script type="text/javascript" src="jquery.min.js"></script>
		<script type="text/javascript">
			
			$(function(){	
				$("#d1").addClass("x")	
			})
		</script>
	</head>
	<body>
		<div id="d1" class="y"></div>
	</body>
</html>

对比javascript和jQuery对标签设置属性的方式得出jQuery更强大

举报

相关推荐

0 条评论