一个元素上的多个 jQuery 事件具有不同的功能和目标选择器

2023-12-29

有没有办法结合这两种方法来处理 jQuery 中的事件附件?

$('selector').on({
    mouseenter: function() {},
    mouseleave: function() {},
    mousedown:  function() {},
    mouseup:    function() {}
});

我更喜欢以前的方法,但需要类似下面的方法来处理“实时”事件(问题是,如果处理程序之间有注释,这将不起作用):

$(document).on('mouseenter', 'selector1', function(){})
           .on('mouseleave', 'selector2', function(){})
           .on('mousedown',  'selector3', function(){})
           .on('mouseup',    'selector4', function(){});

但是,有没有解决方法可以这样做?:

$(document).on({
    mouseenter: 'selector1': function() {},
    mouseleave: 'selector2': function() {},
    mousedown:  'selector3': function() {},
    mouseup:    'selector4': function() {}
});

Update

我最终得到了这个简单的结果on- 包装函数:https://gist.github.com/4191657 https://gist.github.com/4191657

用法非常简单:

$(document).act(
    ['mouseenter', 'selector1', function() {}],
    ['mouseleave', 'selector2', function() {}],
    ['mousedown', 'selector3', function() {}],
    ['mouseup', 'selector4', function() {}]
);

对此有何建议或改进?


查看 jQuery 文档.on() method http://api.jquery.com/on/。当您使用第一个示例中使用的事件映射版本时,您可以传递选择器作为第二个参数:

$(document).on({
    mouseenter: function() {},
    mouseleave: function() {},
    mousedown: function() {},
    mouseup: function() {}
}, "selector");

这假设您希望对所有这些事件使用相同的选择器。如果可能不同,您最好的选择可能是将调用链接到.on():

$(document).on('mouseenter', 'selector1', function(){})
           .on('mouseleave', 'selector2', function(){})
           // ...etc
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

一个元素上的多个 jQuery 事件具有不同的功能和目标选择器 的相关文章

随机推荐