Jquery removes binds and triggers element events using examples

  • 2020-03-30 02:36:21
  • OfStack


unbind(type [,data])     //Data is the function to remove
$('#btn').unbind("click"); //Remove the click
$('#btn').unbind(); //Remove all

For cases that only need to be triggered once and then immediately unbound, use one()


$('#btn').one("click",function(){.......});

Triggering action
The trigger() method fires the specified event type of the selected element.


$('#btn').trigger("click");

You can also execute events directly


$('#btn').click();

Triggers a custom event
The bind() method adds one or more event handlers to the selected element and specifies the function to run when the event occurs.


$('#btn').bind("myclick",function(){....});

The simulation fires the above binding function


$('#btn').trigger("myclick");

Pass the data trigger(event,[param1,param2,...] )


$('#btn').bind("myclick",function(event,message1,message2){...........});
$('#btn').trigger("myclick",[" To pass to message1"," To pass to message2"]);

Triggers the default action


$("input").trigger("focus");
//Not only does it trigger the focus event bound to the input element, but it also triggers the default action of getting focus

Only binding events are triggered, not browser defaults


$("input").triggerHandler("focus");
//Only binding events are triggered, not browser defaults

Other USES

Bind multiple event types


$("div").bind("mouseover mouseout",function(){.....});

Add the event namespace


$("div").bind("click.plugin",function(){......});

Add a namespace after the bound world type so that you only need to specify the namespace when deleting an event.


$("div").unbind(".plugin");   //Deletes events in space
$("div").trigger("click!"); //The click method is not included in the namespace because it is triggered

Also fires if contained in the namespace


$( " div " ).trigger( " click " );

Cancels or binds functions


$('div').bind('click', RecommandProduct);//Bind the RecommandProduct function for div
$('div').unbind('click', RecommandProduct);//Cancel the RecommandProduct function


Related articles: