Jquery trigger()方法
trigger()方法用于为每个匹配的元素触发指定的事件处理程序。此方法还可用于触发所选元素的默认行为。
语法
使用
trigger()的常用语法/strong>方法如下:
$(selector).trigger(event,param1,param2,...)
此方法具有一个必需参数,并且可以具有多个可选参数。
参数值
event: 必填参数。它指定一个事件以触发特定元素。可以是标准事件,也可以是自定义事件。
param1,param2,...: 这些是可选的,还可以作为参数传递给事件处理程序的其他参数。它们对自定义事件很有用。
让我们看看使用
trigger()方法的一些说明。
Example1
在此示例中,单击给定段落元素时,将使用
trigger()方法触发输入元素的
select 事件。触发select事件时,它将更改输入字段和文档正文的样式。
此处,我们使用
的强制性 event 参数trigger()方法。
<!DOCTYPE html>
<html>
<head>
<title> jQuery trigger() method </title>
<script src="/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#p2 {
border: 2px solid red;
width: 60px;
text-align: center;
}
</style>
<script>
$(document).ready(function(){
$("p").click(function(){
$("#tf").trigger("select");
});
$("#tf").select(function(){
$("#tf").css({"backgroundColor": "yellow", "fontSize": "25px"});
$("body").css({"backgroundColor": "lightgreen", "fontSize": "25px"});
});
});
</script>
</head>
<body>
<h4> This is an example of using the jQuery trigger() method </h4>
<input id = "tf" type = "text" value = "Text here...">
<br>
<p id = "p1"> Click the following text to see the effect. </p>
<p id = "p2"> Click me </p>
</body>
</html>
输出:
执行上述代码后,输出将为-
单击给定的段落元素后,输出为-
Example2
在此示例中,我们使用
trigger()的可选参数方法。这些附加参数作为参数传递给事件处理程序。
<!DOCTYPE html>
<html>
<head>
<script src = "/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#p2 {
border: 2px solid red;
width: 60px;
text-align: center;
}
</style>
<script>
$(document).ready(function(){
$("#p2").click(function () {
$("#p2").bind("custom", function(event, id, name, salary){
alert("Employee ID = " + id + "\nName = " + name + "\nSalary = " + salary);
});
$("#p2").trigger("custom", ["E01", "John", "30,000"]);
});
});
</script>
</head>
<body>
<h4> This is an example of using the jQuery trigger() method </h4>
<p id = "p1"> Click the following text to see the effect. </p>
<p id = "p2"> Click me </p>
</body>
</html>
输出:
执行上述代码后,输出将为-
单击给定的段落元素后,输出为-