2010-08-18 92 views
3

我不是最好的jQuery的東西。但我試圖從函數中分離出動作,這樣我就可以應用多個導致相同功能的事件。不幸的是,這是行不通的。有人知道爲什麼如何將多個事件應用於相同的功能

更新功能,但仍錯誤

$(document).ready(function() { 

var $info_items = jQuery('.checkbox.has_info, .has_info'); 

$info_items.click(function(event) { 
$(this).show_text(event); 
}); 


// I suspect it has something to do with this initalizer of the function here 

jQuery.fn.show_text = function(event){ 
    var $info_item = jQuery(this); 
    $info_items.filter(function(index){ 
    return $(".hidden_text").css("display","block"); 
    }).not($info_item).parent().next().next().hide("slow"); 
    $info_item.parent().next().next().show("fast"); 
}); 

}); 
+0

下次請使用更好的主題行。也許就像「如何將多個事件應用於同一個功能」。 – Bart 2010-08-18 18:18:30

回答

7

什麼是e,事件?您需要將事件參數命名爲click()函數才能使用它。此外,援引show_text使得其具有一個this,你需要調用它的一個元素:

$info_items.click(function (event) { 
    // 'this' is the element in $info_items which was clicked 

    // invoke show_text on the element in question 
    $(this).show_text(event); 
}); 

你也對你的最終});線有一個額外的)

+0

我想也許我不得不通過一個事件來讓它「工作」。但我已經把它拿出來了,但它仍然錯誤。我理解你的例子,但我試圖不這樣做,以便我可以有多個事件觸發相同的功能。 – Trip 2010-08-18 18:15:09

+0

感謝您的更新。我試過了,它仍然是炸彈。如果我評論整個功能,那很好。 ;)。所以也許初始化語法在我的結尾是錯誤的? – Trip 2010-08-18 18:19:14

+0

你在'$(function(){})'內執行這個嗎?什麼是'$ info_items'?沒有更多信息,我們無法提供幫助。 – meagar 2010-08-18 18:25:53

2

您可以使用jQuery bind將多個事件附加到單個函數。

$('#whatever').bind('mouseover focus click', function() { 
    your_custom_function(); 
}); 
2

你在找這樣的嗎?

var handle = function(event) { 
    $(event.currentTarget).show_text(event); 
}; 
$info_items.bind('click blur', handle); 
+0

聽衆是否必須明確後來的功能? – Trip 2010-08-18 18:32:12

+0

如果你將你的處理函數定義爲局部變量,那麼是的。如果你將它定義爲一個命名函數(即使它是一個本地命名函數),監聽器可以優先。 – jdc0589 2010-08-18 18:34:03