jquery中trigger() 方法触发被选元素的指定事件类型了,但有使用过程中会碰到一些问题了,下面我们一起来看看jQuery中trigger()触发hover事件疑问,希望对各位有帮助。
今天做一个项目,遇到了一个问题,是以前没有遇到过的,就此记上一笔。
1、trigger方法解释
官方是这么解释的:
复制代码 代码如下:
Description: Execute all handlers and behaviors attached to the matched elements for the given event type.
用法:
.trigger( eventType [, extraParameters] )
其中eventType包含javascript内置的事件、jQuery增加的事件和自定义事件。例如:
?
1 2 3 4 5 6 7 8 9 10 $('#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']);很强大,常常用于页面初始化的时候使用。
2、trigger遇到hover
?
1 2 3 4 5 6 7 8 9 var $search=$('#header .search'); $search.find('li').hover(function() { alert(1); },function() { alert(2); }); $search.find('li').eq(0).trigger('hover');无法触发hover。但是:
?
1 2 3 4 5 6 7 8 9 var $search=$('#header .search'); $search.find('li').click(function() { alert(1); },function() { alert(2); }); $search.find('li').eq(0).trigger('click');触发click正常!
解决办法:
?
1 2 3 4 5 6 7 8 9 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同样的情况存在于jQuery.live(),不过live不推荐在1.7以后版本使用,使用on()代替。
以上所述就是本文的全部内容了,希望大家能够喜欢。