2010-08-18 35 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

相关问题