I was working on a project today and encountered a problem that I have never encountered before, so I made a note of it.
1. Explanation of trigger method
This is the official explanation:
Usage:
.trigger( eventType [, extraParameters] )
The eventType includes javascript built-in events, jQuery-added events and custom events. For example:
$('#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']);
is very powerful and is often used during page initialization.
2. Trigger meets 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');
Triggering click is normal!
Solution:
var $search=$('#header .search'); $search.find('li').hover(function() { alert(1); },function() { alert(2); }); $search.find('li').eq(0).trigger('mouseenter');//hover修改为mouseenter/mouseleave/mouseover/mouseout
The same situation exists with jQuery.live(), but live is not recommended for use in versions after 1.7. Use on() instead.
The above is the entire content of this article, I hope you all like it.