向动态添加的元素添加侦听器

向动态添加的元素添加侦听器

问题描述:

我有一个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();
});