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

  • Post author:
  • Post category:java




第一种方式:用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更强大



版权声明:本文为YZL40514131原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。