无法获取jQuery on()来注册动态添加的内容 [英] Unable to get jQuery on() to register dynamically added content

查看:186
本文介绍了无法获取jQuery on()来注册动态添加的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jQuery中的on()方法很新,但是我需要使用它的时候了。

I'm quite new to the on() method in jQuery but the time has come for me to need to use it.

我有两个功能点击具体按钮。每个函数都适用于最初在页面上的任何元素,但不适用于任何动态添加的内容(更多相同的按钮)。我明白,在阅读本文和Google上的其他答案后,我需要使用on()函数,但仍然有麻烦。无论如何,代码:

I've two functions for clicking on specific buttons. Each function works on any elements originally on the page but not on any dynamically added content (more of the same buttons). I understand I need to use the on() function after reading other answers on here and on Google but am having trouble still. Anyway, code:

jQuery("ul#THEBUTTONS").on({
    click: function(event){
        event.preventDefault();
        console.log("apaz clicked");
    }
}, "a.azaz");


jQuery("ul#THEBUTTONS").on({
    click: function(event){
        event.preventDefault();
        console.log("mapaz clicked");
    }
}, "a.mapaz");

任何帮助将非常感谢,在这里撕开我的头发。

Any help would be immensely appreciated, tearing my hair out here.

推荐答案

.on()基本上有两种口味:一种类似于。 bind(),另一个类似于 .delegate()

.on() essentially has two flavors: one which acts like .bind(), and another which acts like .delegate().

你的问题,你想使用委托版本。作为参考,签名中的如下所示:

For your problem, you want to use the delegate version. As a reference, on signatures are like this:

// bind
$(element-selector).on(event, handler)

// delegate
$(container-selector).on(event, element-selector, handler)

加快速度的最好方法可能是读取委托 ,它是如何使用的,然后应用于

The best way to get up to speed with this is probably to read up on delegate, what it is, how its used, and then apply that to on.

这篇关于无法获取jQuery on()来注册动态添加的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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