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

查看:20
本文介绍了无法让 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(),另一种类似于 .bind()另一个类似于 .delegate().

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

对于您的问题,您想使用 delegate 版本.作为参考,on 签名是这样的:

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)

了解这一点的最佳方法可能是阅读delegate,它是什么,如何使用,然后将其应用于 on.

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天全站免登陆