views:

38

answers:

2

I know that live() can be used to support event handlers for current AND "added later" DOM elements.

I wonder how to do the same thing with each()?

Like if I have $('.something_or_other').each() but then another DOM element with class="something_or_other" gets added? How can I set it up to automatically apply the each iteration to this new DOM element?

OR, what can I call after adding the new DOM element to reapply the each() rules.

(Showing my age a bit here but in Behaviour we can use Behaviour.apply() to reapply ALL of the rules!)

A: 

Why can't you just bind the functionality to the ajax callback that appends the DOM elements to the doc? Seems the shortest and most logical route to me.

meder
What functionality! I'm hoping that there's an automatic way to do it. But also I would like to know how I could do it manually. Do I have to repeat all of the code in the each() iteration specifically for the new added element??!??
Dougal
A: 

As @meder noted, you should really just do this manually. You can use the same function for both if you like.

function myFunction(i,val) {
    $(this).doSomething;
}

$('someSelector').each( myFunction );

$.ajax({
    url:'/some/path/',
    success: function( data ) {
        $(data).find('someSelector').each( myFunction )
               .end().appendTo('body');
    }
});

If you really don't want to do that, there's a plugin called livequery that will run code when an element that matches a selector is added to (or removed from) the DOM.

It costs a bit of extra overhead, but it is an option.

http://brandonaaron.net/code/livequery/docs

patrick dw
livequery looks like what I was thinking. Thanks. Other people's points are also very valid.
Dougal