jQuery中trigger()觸發hover事件疑問

來源:互聯網
上載者:User


今天做一個項目,遇到了一個問題,是以前沒有遇到過的,就此記上一筆。

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.