向动态添加的元素添加侦听器 [英] Add a listener to an element that is dynamically added

查看:83
本文介绍了向动态添加的元素添加侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript / jQuery页面,我正在使用Twitter Bootstrap的typeahead。在javascript中有两个单独的地方,我添加了我想要打字的元素。在没有要求主观答案的情况下,对于我来说,动态地将输入注册为预先输入是一种好方法吗?给他们所有不同的ID并在每次添加时注册?使用 .on()是否可以完成任何魔术?

I have a javascript/jQuery page where I'm using Twitter Bootstrap's typeahead. There are two separate places in the javascript where I add elements that I would like to be typeaheads. Without asking for subjective answers, what's a good way for me to register the inputs as typeaheads dynamically? Give them all different ID's and register every time I add them? Is there any magic that can be done with .on()?

推荐答案

您可以使用 jQuery 委派来执行此操作。例如:

You can use jQuery delegation to do that. For example:

$("#element-that-will-contain-typeaheads").on("DOMNodeInserted", function () {
    $(this).find(".typeahead").typeahead();
});

这篇关于向动态添加的元素添加侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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