HTML中给HTML元素添加事件

方法一:

代码示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script>
			function test(){
				console.log("hello world!");
			}
		</script>
	</head>
	<body>
		<input type="button" value="按钮" onclick="test()" />
	</body>
</html>

方法二:

代码示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<input type="button" value="按钮" id="button" />
		<script>
			document.getElementById("button").onclick=function(){
				console.log("hello world!");
			}
		</script>	
	</body>
</html>

方法三:

代码示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<input type="button" value="按钮" id="button" />
		<script>
			document.getElementById("button").addEventListener("click",function(){
				console.log("hello world!");
			})
		</script>
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/m0_46383618/article/details/107427090