2010-04-23 96 views
3

我需要以編程方式觸發由jQuery處理的點擊事件。下面是當前的代碼:jQuery - 以編程方式觸發事件

var $thumbs = $('#PhotoGalleryThumbs .tile'); 
var $zoom = $('#PhotoGallery #PhotoGalleryZoom img'); 
var $description = $('#PhotoGallery #PhotoGalleryDescription'); 

$thumbs.click(function(event) { 
    event.preventDefault(); 
    var $thumb = $(this); 
    $thumb.addClass('selected') 
     .siblings().removeClass('selected'); 
    $zoom.attr('src', $thumb.children('a').attr('href')); 
    $description.html($thumb.find('img').attr('alt')); 
}); 

我有心理障礙工作如何創建一個函數進行事件處理代碼,然後任意調用它在$thumbs對象的元素。

回答

5
$thumbs.click(); 

這會觸發點擊事件。這是你在找什麼?

+0

或者,您可以專門定位給定元素,而不是整個集合。 '$('#yourTarget')。click();' – 2010-04-23 16:33:56

+0

$ thumbs是一組對象。我想選擇一個特定的對象,然後調用'click()'事件。 – Sonny 2010-04-23 16:38:20

+0

as S Pangborn said,$('#yourSpecificElement')。click() – 2010-04-23 16:45:44

2

$($thumbs[7]).click(); 

以前的建議類似,您可以使用

$thumbs.eq(7).click(); 

爲了澄清,數組索引到一個jQuery集合讓你的DOM元素在該位置,而.eq(n)給你一個新的jQuery對象,它只引用索引元素。

http://api.jquery.com/eq/

+0

謝謝傑夫,我肯定會把它放在我的後兜裏! – Sonny 2010-04-26 13:18:31

相關問題