jQuery - how to repeat a function within itself to include nested files
Posted
by brandonjp
on Stack Overflow
See other posts from Stack Overflow
or by brandonjp
Published on 2010-03-13T01:04:24Z
Indexed on
2010/03/13
1:07 UTC
Read the original article
Hit count: 312
I'm not sure what to call this question, since it involves a variety of things, but we'll start with the first issue...
I've been trying to write a simple to use jQuery for includes (similar to php or ssi) on static html sites. Whenever it finds div.jqinclude
it gets attr('title')
(which is my external html file), then uses load()
to include the external html file. Afterwards it changes the class of the div to jqincluded
So my main index.html might contain several lines like so:
<div class="jqinclude" title="menu.html"></div>
However, within menu.html there might be other includes nested. So it needs to make the first level of includes, then perform the same action on the newly included content. So far it works fine, but it's very verbose and only goes a couple levels deep.
How would I make the following repeated function to continually loop until no more class="jqinclude"
elements are left on the page? I've tried arguments.callee
and some other convoluted wacky attempts to no avail.
I'm also interested to know if there's another completely different way I should be doing this.
$('div.jqinclude').each(function() { // begin repeat here
var file = $(this).attr('title');
$(this).load(file, function() {
$(this).removeClass('jqinclude').addClass('jqincluded');
$(this).find('div.jqinclude').each(function() { // end repeat here
var file = $(this).attr('title');
$(this).load(file, function() {
$(this).removeClass('jqinclude').addClass('jqincluded');
$(this).find('div.jqinclude').each(function() {
var file = $(this).attr('title');
$(this).load(file, function() {
$(this).removeClass('jqinclude').addClass('jqincluded');
});
});
});
});
});
});
© Stack Overflow or respective owner