多个选择器上的jQuery on()方法 [英] jQuery on() method on multiple selectors

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

问题描述

由于版本1.7 live 已弃用。

Since version 1.7 live is deprecated.

以下示例很容易与新<$ c兼容$ c> on 方法:

Following example is easy to make compatible with new on method:

$('nav li, #sb-nav li, #help li').live('click', function () {
    // code...
});

在上使用

Using on:

$('nav, #sb-nav, #help').on('click', 'li', function () {
    // code...
});

如何在重写以下示例c>?

How to rewrite following example using on?

 $('#header .fixed-feedback-bn, #sb-sec .feedback-bn').live('click', function () {
     // code...
 });


推荐答案

$(document).on('click', '#header .fixed-feedback-bn, #sb-sec .feedback-bn', function () {
     // code...
 });

.live()只是绑定文件作为倾听者。

.live() is just binding document as listener.

我的两分钱是你几乎总能找到比文件更好的倾听者。至少,几乎所有页面都使用主内容包装器。这会消除页眉,页脚和有时侧边栏中的节点作为侦听器。

My two cents are that you can almost always find a better listener than document. At bare minimum, almost all pages use a main content wrapper. This eliminates nodes in the header, footer, and sometimes sidebars as listeners.

使用 .on 的最佳方式作为委托功能是识别最接近的共同祖先,预期永远不会被销毁或以其他方式使事件不受约束。例如,如果您有一个由ajax请求更新和更改的表单,则侦听器可以是表单节点本身(如果只更新表单的内容)或包含表单的容器元素(通常是div)。如果没有这样的div,你可以随时添加它,或者你可以将树上到下一个祖先。

The best way to use .on as a delegating function is to identify the nearest common ancestor that is expected to never be destroyed or otherwise have events unbound. For example, if you have a form that gets updated and changed by ajax requests, the listener could be the form node itself (if only the contents of the form are updated) or a container element (generally a div) that surrounds the form. If such a div isn't there, you could always add it in, or you could just go up the tree to the next ancestor.

在提供的特定示例代码中,很难说是否有更好的侦听器包含 #header 还有#sb-sec 。但想象这些东西与idmainContainer共享一个祖先,你的更有效的代码只是交换出监听器:

In the particular sample code provided, it's hard to say if there's a better listener that would contain both #header and also #sb-sec. But imagining that these things share an ancestor with the id "mainContainer", your more efficient code simply swaps out the listener:

$('#mainContainer').on('click', '#header .fixed-feedback-bn, #sb-sec .feedback-bn', function () {
   // code...
});

这篇关于多个选择器上的jQuery on()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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