网络编程 
首页 > 网络编程 > 浏览文章

jquery中trigger()无法触发hover事件的解决方法

(编辑:jimmy 日期: 2025/12/27 浏览:3 次 )

今天做一个项目,遇到了一个问题,是以前没有遇到过的,就此记上一笔。

1、trigger方法解释

官方是这么解释的:

复制代码 代码如下:
Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

用法:
.trigger( eventType [, extraParameters] )

其中eventType包含javascript内置的事件、jQuery增加的事件和自定义事件。例如:

$('#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

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

无法触发hover。但是:

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

触发click正常!

解决办法:

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()代替。

以上所述就是本文的全部内容了,希望大家能够喜欢。

上一篇:JS基于面向对象实现的放烟花效果
下一篇:javascript实现的图片切割多块效果实例
一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。