【问题标题】:How to apply multiple events to the same function如何将多个事件应用于同一个函数
【发布时间】:2011-03-31 17:20:40
【问题描述】:

我不是最擅长这个 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");
});

});

【问题讨论】:

  • 下次请使用更好的主题行。可能类似于“如何将多个事件应用于同一个函数”。

标签: javascript jquery oop function


【解决方案1】:

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

您的最后一行 }); 上还有一个额外的 )

【讨论】:

  • 我想也许我必须向它传递一个事件才能使“this”工作。但是我把它拿出来了,它仍然会出错。我理解你的例子,但我尽量不这样做,这样我就可以让多个事件触发同一个函数。
  • 感谢更新。我试过这个,它仍然是炸弹。如果我注释掉整个函数,那很好。 ;) 。那么也许我的初始化语法是错误的?
  • 您是否在$(function() { }) 中执行此操作? $info_items 是什么?没有更多信息,我们无能为力。
  • 在上面添加了 $info_items ;) 这也在 $(document).ready(function() {
  • 另外,您的浏览器是否给您一个错误消息?如果没有,请通过 Firefox 运行您的代码并安装 Firebug。
【解决方案2】:

您可以使用 jQuery bind 将多个事件附加到单个函数。

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

【讨论】:

    【解决方案3】:

    你在寻找这样的东西吗?

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

    【讨论】:

    • 监听器是否必须显式地出现在函数之后?
    • 如果您将处理程序函数定义为局部变量,是的。如果将其定义为命名函数(即使它是本地命名函数),侦听器可以先来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2018-07-29
    • 2022-11-04
    • 2019-10-19
    • 2019-03-13
    • 2021-10-01
    • 1970-01-01
    相关资源
    最近更新 更多