如何将多个事件应用于同一函数

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");
});

});

下次请使用更好的主题行。也许可以使用“如何将多个事件应用于同一函数”这样的内容。 - Bart
3个回答

7

什么是事件e?调用click()函数需要为事件参数命名。此外,要使用this调用show_text,需要在元素上调用它:

$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);
});

您的最后一行});上还多了一个)

我曾以为可能需要将事件传递给它,以使'this'起作用。但是我已经将其删除,它仍然出错。我理解你的例子,但我试图避免这样做,以便可以有多个事件触发相同的函数。 - Trip
谢谢更新。我试了一下,它仍然出错。如果我把整个函数注释掉,就没问题了。所以也许是我初始化语法有误? - Trip
你是在 $(function() { }) 中执行这个吗? $info_items 是什么?没有更多的信息,我们无法提供帮助。 - user229044
添加$info_items在上面;;) 这也位于$(document).ready(function() { 中。 - Trip
另外,你的浏览器是否给出了错误信息?如果没有,请通过Firefox运行您的代码并安装Firebug。 - user229044
运行Firebug。但它给了我一些其他随机错误,而不是告诉我它在哪里出错,导致整个JavaScript库出现错误。 :( - Trip

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);

监听器必须明确放置在函数之后吗? - Trip
如果您将处理程序函数定义为本地变量,则是的。如果您将其定义为命名函数(即使它是本地命名函数),则侦听器可以放在前面。 - jdc0589

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接