lundi 13 février 2017

Jquery recursive function providing wrong result

Vote count: 0

I tried to build multilevel menu structure. For this i create a recursive function for making JSON with all menu option. But i am suffering from an anonymous problem within recursive function in jquery. my recursive function added elements multiple times.

Here is my sample code which describe my problem -



var main_menu_list = [];
  $('#div_menu_items ul#ul_main_container > li').each(function (i, z) {
     var menu_id = $(z).attr('menu_id');                    
     main_menu_list.push({"menu_id": menu_id});
     checkSubMenu(z, menu_id);

function checkSubMenu(obj, parent_menu_id) {
 if ($(obj).children('ul').length > 0) {
    if ($(obj).children('ul').find('li').length > 0) {
      $(obj).children('ul').find('li').each(function (j, el) {
            var menu_id = $(el).attr('menu_id');
            main_menu_list.push({"menu_id": menu_id});
                    checkSubMenu(el, menu_id);

For this sample html code alert following JSON [{"menu_id":"1"},{"menu_id":"3"},{"menu_id":"8"},{"menu_id":"8"}]. here you can see the result have menu id 8 multiple times. I am not able to understand why this is happened? Can any one help me to override this problem?

Thank you very much in advance...!!!

asked 41 secs ago

Let's block ads! (Why?)

Jquery recursive function providing wrong result

Aucun commentaire:

Enregistrer un commentaire