I paste all of my code because it might have a connection with the function I am asking for. I had help to make one of my functions run. Look at the parseJSON() function. Why I have to use 2 functions (parseJSON() and nested makeNav(navigation)), but not only one parseJSON(navigation) (and ofc to change the inner elements from makeNav to parseJSON). Can someone explain why it works only that way for me. Because I want to understand it, not just to do my exercise and go on.
var new_json;
$.get('navigation.json', function (json){
new_json = json;
parseJSON();
var reload_page;
var this_hash = window.location.hash;
if( this_hash.length == 0 ){
reload_page = "home";
}else{
reload_page = this_hash.replace('#', '');
};
loading(reload_page + '.html');
});
var cache = {};
function loading(url){
if( typeof(cache[url]) == 'undefined' ) {
console.log( 'cache A does not exists' );
container.load(url + ' .container>*', function(){
cache[url] = container.html();
});
}else {
console.log( 'cache A exists' );
container.html(cache[url]);
};
};
$('#navigation li a, #logo a').live('click',function(){
var url = $(this).attr('href');
window.location.hash = url.replace('.html', '');
loading(url);
return false;
});
function parseJSON() {
function makeNav(navigation) {
var nav_html = '';
console.log( navigation.length );
for (var i = 0; i < navigation.length; i++) {
var name = navigation[i]['name'];
var href = navigation[i]['href'];
var submenu = navigation[i]['navigation'];
nav_html += '<li><a href="' + href + '">' + name + '<span class="ddArrow"></span></a>';
if( typeof(submenu) != 'undefined' ){
nav_html += '<ul>';
nav_html += makeNav(submenu);
nav_html += '</ul>';
}
nav_html += '</li>';
}
return nav_html;
}
$('#navigation ul').html(makeNav( new_json['navigation'] ));
}
Probable reason is that your
parseJSONdoes extra things:$('#navigation ul').html(makeNav( new_json['navigation']));and when you make recursive call tomakeNavyou don’t need to set this html content. Reason for the nested definition ofmakeNavinsideparseJSONcould be that you don’t wantmakeNavto be visible outside of the scope ofparseJSONbecause you simply don’t use it out of this scope and you don’t want to pollute the “environment”.Anyway, I really don’t think that’s the best way to implement it…but that should be discussed at https://codereview.stackexchange.com/.
To use a single function, without the nested
makeNavyou can do something like: