jQuery:使用委托时链接on() [英] jQuery: Chaining on() when using delegation

查看:77
本文介绍了jQuery:使用委托时链接on()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去,我曾经非常成功地将呼叫链接到live(),例如:

In the old days, I used to chain calls to live() with great success, e.g.:

$(".something")
    .live("click", function(e) { ... })
    .live("change", function(e) { ... })
    .live("submit", function(e) { ... });

这些天live()bind()delegate()已被闪亮的新on()取代.

These days, live(), bind() and delegate() have been superseded by the shiny new on().

我试图简单地将live()替换为on(),这似乎很明显:

I've tried simply replacing live() with on() which would seem obvious:

$(".something")
    .on("click", function(e) { ... })
    .on("change", function(e) { ... })
    .on("submit", function(e) { ... });

但是,当您考虑on()的工作原理时,这显然是行不通的.来自 http://api.jquery.com/on/:

However, it's almost as obvious that this won't work when you consider how on() works. This from http://api.jquery.com/on/:

事件处理程序仅绑定到当前选定的元素;在您的代码调用.on()时,它们必须存在于页面上."

"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

根据jQuery文档,我需要绑定到document并委托给.something来处理实时事件.不幸的是,这意味着如果我想用on()复制上面的内容,我最终将重复我的委托选择器(.document):

According to the jQuery docs, I need to bind to document and delegate to .something to handle live events. Unfortunately, this means I end up repeating my delegate selector (.document) if I want to replicate what I have above with on():

$(document)
    .on("click", ".something", function(e) { ... })
    .on("change", ".something", function(e) { ... })
    .on("submit", ".something", function(e) { ... });

这可以按预期工作,但是我真的很希望能够像使用live()一样更清晰地链接.我想念什么吗?

This works as expected but I'd really love to be able to chain more clearly like I do using live(). Am I missing something?

推荐答案

我相信您可以做到:

$(document).on({
    "click" : function(e) { ... },
    "change" : function(e) { ... },
    "submit" : function(e) { ... }
}, ".something");

也就是说,使用"events-map"语法指定事件及其处理程序,然后指定用于委托人风格行为的选择器.

That is, use the "events-map" syntax to specify the events and their handlers, and then specify the selector to use for the delegate-style behaviour.

这篇关于jQuery:使用委托时链接on()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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