HTML this 参数在JS中的使用方法

在前端页面中,当我们需要为当前标签绑定某个事件时,一般的思路是给其绑定一个独一无二的id,但是当我们们的代码量比较大的时候,id命名就会变得很困难,而且对于每一个元素都要写一个js事件,这是代码重复就会产生,this指针的出现解决了这一现象,他会自动给js函数绑定当前标签,下边是一个实例:

实现鼠标放到div块上颜色改变:

<html>
	<head>
	</head>
	<body>
		<div style="width:300px;height:300px;background:#aaa;display:block;" onmouseover="show(this)" onmouseout="mOut(this)"></div>
		<script>
			function show(obj){
				obj.style.background="#faa";
			}
			function mOut(obj){
				obj.style.background="#aaa";
			}
		</script>
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_39429962/article/details/82872878