HTML 练习绑定onclick事件

时间:2023-02-06 03:16:10

方法一

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p onclick="func1(this)">hello p</p> <script>
function func1(self){
alert(self.innerHTML);
} </script>
</body>
</html>

方法二

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p id="p1">hello p</p>
</body>
<script>
var ele = document.getElementById("p1")
ele.onclick=function (){
alert(this.innerHTML)
} </script>
</html>

方法三

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p class="p">hello p1</p>
<p class="p">hello p2</p>
</body>
<script>
var ele = document.getElementsByClassName("p")[0];
ele.onclick=function(){
alert(this.innerHTML)
}
</script>
</html>

方法四

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.3.1.min.js"></script>
<script>
function f(){
$("p").css("color","red")
}
</script>
</head>
<body>
<p onclick="f()">hello world</p>
</body>
</html>

方法五

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<p>hello world</p>
</body>
<script>
$("p").click(function(){
$(this).css("color","red")
})
</script>
</html>