JQuery .on()方法,具有一个选择器的多个事件处理程序 [英] JQuery .on() method with multiple event handlers to one selector

查看:228
本文介绍了JQuery .on()方法,具有一个选择器的多个事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图弄清楚如何将Jquery .on()方法与具有多个与之关联的事件的特定选择器一起使用。我之前使用过.live()方法,但不太确定如何用.on()完​​成同样的壮举。请参阅下面的代码:

Trying to figure out how to use the Jquery .on() method with a specific selector that has multiple events associated with it. I was previously using the .live() method, but not quite sure how to accomplish the same feat with .on(). Please see my code below:

$("table.planning_grid td").live({
  mouseenter:function(){
     $(this).parent("tr").find("a.delete").show();
  },
  mouseleave:function(){
     $(this).parent("tr").find("a.delete").hide();        
  },
  click:function(){
    //do something else.
  }
});

我知道我可以通过以下方式分配多个事件:

I know I can assign the multiple events by calling:

 $("table.planning_grid td").on({
    mouseenter:function(){  //see above
    },
    mouseleave:function(){ //see above
    }
    click:function(){ //etc
    }
  });

但我相信正确使用.on()会是这样的:

But I believe the proper use of .on() would be like so:

   $("table.planning_grid").on('mouseenter','td',function(){});

有没有办法实现这个目标?或者这里的最佳做法是什么?我尝试了下面的代码,但没有骰子。

Is there a way to accomplish this? Or what is the best practice here? I tried the code below, but no dice.

$("table.planning_grid").on('td',{
   mouseenter: function(){ /* event1 */ }, 
   mouseleave: function(){ /* event2 */ },
   click: function(){  /* event3 */ }
 });

提前致谢!

推荐答案

那是相反的方式。你应该写:

$("table.planning_grid").on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    click: function() {
        // Handle click...
    }
}, "td");

这篇关于JQuery .on()方法,具有一个选择器的多个事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆