Bind custom event after adding a new element
I am using the jQuery Tokenizing autocomplete plugin (http://github.com/loopj/jQuery开发者_如何学Python-Tokenizing-Autocomplete-Plugin) and I create new input types on the client side using the $('selector').after('html'); method. When I do this, the newly created element does not use the plugin.
The initial input is tokenized like this
$('.recipe_ingredient').tokenInput('/ingredients/index.json', {
hintText: 'Type in an ingredient like Tuna, Chicken...',
tokenLimit: 1,
onAdded: ingredient_added,
onRemoved: ingredient_removed,
});
Any new input types matching the selector does not get tokenized, any ideas? I am getting lost in the syntax.
EDIT
I ended up doing something like this
clickedContainer.after('html');
$('#total-i-forms').attr('value', count);
var ri = clickedContainer.next().find('.recipe_ingredient');
ri.tokenInput('/ingredients/index.json', {
hintText: 'Type in an ingredient like Tuna, Chicken...',
tokenLimit: 1,
onAdded: ingredient_added,
onRemoved: ingredient_removed,
});
Is this method preferred over live query?
You can use the .livequery()
plugin for this:
$('.recipe_ingredient').liveQuery(function() {
$(this).tokenInput('/ingredients/index.json', {
hintText: 'Type in an ingredient like Tuna, Chicken...',
tokenLimit: 1,
onAdded: ingredient_added,
onRemoved: ingredient_removed,
});
});
It actively looks for new elements added to the DOM that match the selector and runs the callback function on them. Think .each()
, but it continues to run for new elements that are added.
You'll need to bind it to any new inputs. The point at which the plugin method is run binds it only to those elements that exist in the DOM at that point.
精彩评论