jQuery click()方法
jQuery的click()是一个内置的方法,可以启动点击事件或附加一个函数,在点击事件发生时运行。
语法:
$(selector).click(function);
参数:它接受一个可选的参数 “函数”,用于在发生点击事件时运行。
jQuery例子显示click()方法的工作:
例子1:在下面的代码中,没有向这个方法传递任何函数。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<!-- jQuery code to show the working of this method -->
<script>
(document).ready(function() {
("p").click();
});
</script>
<style>
p {
display: block;
width: 300px;
padding: 20px;
font-size: 30px;
border: 2px solid green;
}
</style>
</head>
<body>
<!-- click on this method -->
<p onclick="alert('paragraph was clicked')">
This is a paragraph.
</p>
</body>
</html>
输出:
例子2:在下面的代码中,函数被传递给这个方法。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
<!-- jQuery code to show the working of this method -->
(document).ready(function() {
("p").click(function() {
$(this).fadeOut();
});
});
</script>
<style>
p {
display: block;
width: 370px;
padding: 25px;
font-size: 25px;
border: 2px solid green;
}
</style>
</head>
<body>
<!-- click on this paragraph and
the paragraph will disappear -->
<p>Click inside this block and
whole block will disappear !!!</p>
</body>
</html>
输出: