An example of the difference between jquery's trigger and triggerHandler

  • 2020-03-30 02:40:26
  • OfStack

Both the trigger and the triggerHandler simulate the occurrence of an event and describe the difference in terms of a specific case
 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<title>test</title> 
<script src="http://code.jquery.com/jquery-1.10.2.js"></script> 

</head> 
<body> 
<input type="checkbox" /> 
<input type="text" id="test"/> 
<input type="button" value="button" id="bnt" onclick="bntClick()"/> 
</body> 

<script> 
$( document ).ready(function() { 
$("input[type='checkbox']").bind("click",function(){ 
$("#test").val("www.baidu.com"); 
}); 
}); 

function bntClick(){ 
$("input[type='checkbox']").trigger("click"); 
} 
</script> 
</html> 

When you click on the checkbox, the checkbox checks and assigns the input[type='text'] value to www.baidu.com

The same thing happens when you click input[type='button']

Replace the trigger with a triggerHandler and when you click on the input[type='button'] you just assign the input[type='text'] without checking the checkbox

The triggerHandler blocks the default behavior of the element that binds the event

Related articles: