jQuery .on('click')与.click()和.delegate('click') [英] jQuery .on('click') vs. .click() and .delegate('click')

查看:83
本文介绍了jQuery .on('click')与.click()和.delegate('click')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于使用.click()delegate('click'),因此当我在jQuery的最新版本中不赞成使用它们时,我以为我会读懂它,但是我有点挠头. /p>

文档此处似乎表明这是.live() .click().bind()具有不同的行为,即绑定到当前存在的对象,其中其他绑定到与该对象匹配的任何对象.选择器模式贯穿DOM的整个寿命.

在大多数情况下,这不会有太大的区别,但是当将元素动态添加到DOM时,这是一个重要的区别.匹配旧模式的新对象将 not 使用.click()绑定到click事件的侦听器,但使用.delegate()绑定.

我的问题是,如何使用.on()方法复制既有.delegate().bind()的行为?还是将来的一切都朝着.delegate()风格发展?

解决方案

仍支持两种模式.

以下对bind()的调用:

$(".foo").bind("click", function() {
    // ...
});

可以直接转换为对on()的以下调用:

$(".foo").on("click", function() {
    // ...
});

以及以下对delegate()的调用:

$("#ancestor").delegate(".foo", "click", function() {
    // ...
});

可以转换为对on()的以下调用:

$("#ancestor").on("click", ".foo", function() {
    // ...
});

为完整起见,以下对live()的调用:

$(".foo").live("click", function() {
    // ...
});

可以转换为以下对on()的调用:

$(document).on("click", ".foo", function() {
    // ...
});

I'm used to using .click() and delegate('click'), so when I read both were deprecated in recent versions of jQuery I thought I'd read up on it, but I'm scratching my head a bit.

The documentation here seems to suggest that this is a drop-in replacement for .live() and .delegate(), but .click() and .bind() had a different behavior, namely binding to currently existing objects, where the others bound to any objects that matched the selector pattern througout the lifespan of the DOM.

In most cases, this wouldn't make a big difference, but when adding elements to your DOM dynamically, this is an important distinction. New objects matching the old pattern would not have listeners tied to the click event using .click(), but would with .delegate().

My question is, how does one use the .on() method to duplicate the behavior of both the pre-existing .delegate() and .bind()? Or is everything in the future going towards the .delegate() style?

解决方案

Both modes are still supported.

The following call to bind():

$(".foo").bind("click", function() {
    // ...
});

Can be directly converted into the following call to on():

$(".foo").on("click", function() {
    // ...
});

And the following call to delegate():

$("#ancestor").delegate(".foo", "click", function() {
    // ...
});

Can be converted into the following call to on():

$("#ancestor").on("click", ".foo", function() {
    // ...
});

For completeness, the following call to live():

$(".foo").live("click", function() {
    // ...
});

Can be converted into the following call to on():

$(document).on("click", ".foo", function() {
    // ...
});

这篇关于jQuery .on('click')与.click()和.delegate('click')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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