trigger of in jquery cannot trigger the resolution of hover events

  • 2020-06-07 04:00:07
  • OfStack

I was working on a project today, but I encountered a problem that I had never encountered before. So Let me write down one.

1. Interpretation of trigger method

Here's the official explanation:


Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

Usage:
.trigger( eventType [, extraParameters] )

eventType contains events built into javascript, events added by jQuery, and custom events. Such as:


$('#foo').bind('click', function()
{
 alert($(this).text());
});
$('#foo').trigger('click');
$('#foo').bind('custom', function(event, param1, param2)
{
 alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

It is very powerful and is often used when a page is being initialized.

2. trigger met hover


var $search=$('#header .search');
$search.find('li').hover(function()
{
 alert(1);
},function()
{
 alert(2);
});
$search.find('li').eq(0).trigger('hover');

hover cannot be triggered. But:


var $search=$('#header .search');
$search.find('li').click(function()
{
 alert(1);
},function()
{
 alert(2);
});
$search.find('li').eq(0).trigger('click');

Trigger click normal!

Solutions:


var $search=$('#header .search');
$search.find('li').hover(function()
{
 alert(1);
},function()
{
 alert(2);
});
$search.find('li').eq(0).trigger('mouseenter');//hover Modified to mouseenter/mouseleave/mouseover/mouseout

The same is true for ES47en.live (), although live is not recommended for use after version 1.7. Use on() instead.

This is the end of this article, I hope you enjoy it.


Related articles: