Introduction
The function of the trigger method is to trigger an event of a specified type on the selected element. The syntax format of its call is: trigger(type,[data]), where the parameter type is the trigger event Type, the parameter data is optional, indicating the attachment parameters passed to the function when the event is triggered.
Commonly used simulation
Sometimes, there is no need to perform operations, but also want to Simulate user operations to achieve certain effects. For example, the click event is triggered after the user enters the interface, without the user having to click.
It can be done using trigger in jquery.
$("#btn").trigger("click")//触发id为btn的click事件 $("#btn").click()//简写
Trigger custom events
trigger can not only trigger these events supported by the browser, but also trigger custom events . For example, bind an event named clickMe:
$("#btn").bind("clickMe",function(){ //.... }) $("#btn").trigger("clickMe")//触发该事件
Transfer data
trigger(type,[data])
The first parameter refers to the type of event triggered, and the second parameter is the additional data to be passed to the event processing function, passed in the form of an array. You can usually distinguish whether this event is triggered by the user by passing a parameter to the callback function.
<button id="btn">按钮</button> <p id="msg"></p> <script> $(function(){ $('#btn').bind("clickMe",function(event,msg1,msg2){ $("#msg").text(msg1+' '+msg2) }) $('#btn').trigger("clickMe",["hello","jquery"]) }) </script>
Effect screenshot
Perform default operation
$('input').trigger('focus')
$('input').triggerHandler('focus')