在JQ中打印obj数组

时间:2017-01-29 18:40:26

标签: javascript jquery html drop-down-menu

首先要说我是JQ和JS的新手,我需要一些帮助。 我该如何打印这个数组

var menu = [
            {
                name: 'Item1',
                submenuName: 'submenu-1',
                subMenu:[
                         {
                            name: 'Item1_1',
                            submenuName: 'submenu-1-1',
                            subMenu:[
                                 {
                                    name: 'Item1_1_1',
                                    submenuName: 'submenu-1-1-1',
                                    subMenu:[
                                             {
                                                name: 'Item1_1_1_1',
                                                submenuName: 'submenu-1-1-1-1',
                                                subMenu:[
                                                         {
                                                            name: 'Item1_1_1_1_1',
                                                            //submenuName: 'submenu-1-1-2',
                                                         },
                                                ]
                                             },
                                             {
                                                name: 'Item1_1_1_2',
                                                //submenuName: 'submenu-1-1-2',
                                             }
                                    ]
                                 },
                                 {
                                    name: 'Item1_1_2',
                                    //submenuName: 'submenu-1-1-2',
                                 },
                            ]
                         },
                         {
                            name: 'Item1_2',
                            //submenuName: 'submenu-1-2',
                         },
                         {
                            name: 'Item1_3',
                            //submenuName: 'submenu-1-3',
                         }
                ]
            },
            {
                name: 'Item2',
                //submenuName: 'submenu-2',
            }
];

查看那样的HTML

<ul data-menu="main" class="menu__level">
    <li class="menu__item"><a class="menu__link" data-submenu="submenu-1" href="#">Item1</a></li>
        <ul data-menu="submenu-1" class="menu__level">
            <li class="menu__item"><a class="menu__link" data-submenu="submenu-1-1" href="#">Item1_1</a></li>
                <ul data-menu="submenu-1-1" class="menu__level">
                    <li class="menu__item"><a class="menu__link" data-submenu="submenu-1-1-1" href="#">Item1_1_1</a></li>   
                        <ul data-menu="submenu-1-1-1" class="menu__level">
                            <li class="menu__item"><a class="menu__link" data-submenu="submenu-1-1-1-1" href="#">Item1_1_1_1</a></li>
                                <ul data-menu="submenu-1-1-1-1" class="menu__level">
                                    <li class="menu__item"><a class="menu__link" href="#">Item1_1_1_1_1</a></li>
                                </ul>

                            <li class="menu__item"><a class="menu__link" href="#">Item1_1_1_2</a></li>
                        </ul>
                    <li class="menu__item"><a class="menu__link" href="#">Item1_1_2</a></li>
                </ul>
            <li class="menu__item"><a class="menu__link" href="#">Item1_2</a></li>
            <li class="menu__item"><a class="menu__link" href="#">Item1_3</a></li>

        </ul>
        <li class="menu__item"><a class="menu__link" href="#">Item2</a></li>
</ul>

我知道我的问题很愚蠢,但我无法弄清楚如何制作它。这将是一个下拉菜单。

3 个答案:

答案 0 :(得分:1)

使用递归:

function getMenuHTML(arr, name) {
  var result = '<ul data-menu="' + (name || 'main') + '" class="menu__level">';
  for (var i = 0; i < arr.length; i++) {
     result += '<li class="menu__item"><a class="menu__link"' + (arr[i].submenuName ? 'data-submenu="' + arr[i].submenuName + '"' : '') + ' href="#">' + arr[i].name + '</a></li>';
     if (arr[i].subMenu && arr[i].subMenu.length) {
        result += getMenuHTML(arr[i].subMenu, arr[i].submenuName);
     }
  }
  result += "</ul>";
  return result;
}

var menu=[{name:'Item1',submenuName:'submenu-1',subMenu:[{name:'Item1_1',submenuName:'submenu-1-1',subMenu:[{name:'Item1_1_1',submenuName:'submenu-1-1-1',subMenu:[{name:'Item1_1_1_1',submenuName:'submenu-1-1-1-1',subMenu:[{name:'Item1_1_1_1_1'},]},{name:'Item1_1_1_2'}]},{name:'Item1_1_2'},]},{name:'Item1_2'},{name:'Item1_3'}]},{name:'Item2'}];

var html = getMenuHTML(menu);
document.getElementById('resultplain').value = html;
document.getElementById('result').insertAdjacentHTML('beforeend', html);
<nav id="result"></nav>
<textarea id="resultplain" style="height: 250px;width:100%"></textarea>

答案 1 :(得分:0)

此功能将构成该菜单:

// createMenu takes an array of objects m and a menuname to be set as data-menu attribute
function createMenu(m, menuname){
    // create the ul
    var ul = document.createElement("ul");
    // if we are at depth 0 then the data-menu should be 'main', else it should be 'submenu-???' depending on the depth
    ul.setAttribute("data-menu", menuname);
    ul.className = "menu__level";

    // now for every object in the menu (m array), create an li element
    m.forEach(function(e){
        // create the li
        var li = document.createElement("li");
        li.className = "menu__item";

        // create the link
        var a = document.createElement("a");
        // set its data-submen attribute and href and text content as well
/******* ONLY IF IT HAS A SUB-MENU *************/
        if(e.subMenu)
            a.setAttribute("data-submenu", e.submenuName);
        a.setAttribute("href", "#");
        a.textContent = e.name;

        // append the link to the li
        li.appendChild(a);

        // append the li to the ul
        ul.appendChild(li);

        // if this object contains a subMenu the create it using createMenu with e.submenuName as menuname 
        if(e.subMenu)
            // if you want it to be appended to the li instead of its parent change 'ul.ap...' to 'li.ap...'
            ul.appendChild(createMenu(e.subMenu, e.submenuName));
    });

    // return the ul element
    return ul;
}

注意:应该像createMenu(menu, "main");一样调用它,其中第一个参数是您的对象数组,第二个参数("main")是data-menu第一个ul

注2: createMenu会返回ul元素,因此您可以将其附加到另一个元素(容器),如下所示:

// create the menu
var myMenuUl = createMenu(menu, "main");
// append it to an element (the body for example)
document.body.appendChild(myMenuUl);

答案 2 :(得分:0)

这是使用两个Javascript模板引擎和模板组合(一种递归形式)的替代解决方案:jsRenderHandlebars。 jsRender检测到jQuery和loads as a jQuery plugin(它们都可以在没有jQuery的情况下使用)。

data-submenu属性已添加到menu__linkhas-submenu类仅在适当时添加到menu__item

注意:我修改了原始的目标HTML,不包含元素ul作为另一个元素ul的子元素(请参阅第一个<li class="menu__item">例如),这将是无效的HTML(检查W3C验证器)。

// Get compiled jsRender template.
var tmpl = $.templates("#entryPointTemplate");

// Get compiled Handlebars template.
var tmplHandlebarsEntryPoint = $("#entryPointTemplate-handlebars").html()
var tmplHandlebarsRenderFunction = Handlebars.compile(tmplHandlebarsEntryPoint);

// Register the subMenuTemplate Handlebars partial.
Handlebars.registerPartial("subMenuTemplate", $("#subMenuTemplate-handlebars").html());

var menu = [ // Source data.
  {
    name: 'Item1',
    submenuName: 'submenu-1',
    subMenu: [{
      name: 'Item1_1',
      submenuName: 'submenu-1-1',
      subMenu: [{
        name: 'Item1_1_1',
        submenuName: 'submenu-1-1-1',
        subMenu: [{
          name: 'Item1_1_1_1',
          submenuName: 'submenu-1-1-1-1',
          subMenu: [{
            name: 'Item1_1_1_1_1',
            //submenuName: 'submenu-1-1-2',
          }, ]
        }, {
          name: 'Item1_1_1_2',
          //submenuName: 'submenu-1-1-2',
        }]
      }, {
        name: 'Item1_1_2',
        //submenuName: 'submenu-1-1-2',
      }, ]
    }, {
      name: 'Item1_2',
      //submenuName: 'submenu-1-2',
    }, {
      name: 'Item1_3',
      //submenuName: 'submenu-1-3',
    }]
  }, {
    name: 'Item2',
    //submenuName: 'submenu-2',
  }
];

// Wrap the data in this way for convenience with the template engines, see: `{{for data}}` and `{{#each data}}`.
var data = {
  data: menu
}

// Render the jsRender template using data.
var htmlJsrender = tmpl.render(data);

// Render the Handlebars template using data.
var htmlHandlebars = tmplHandlebarsRenderFunction(data);

// Insert the rendered (by jsRender) HTML into the DOM.
$("#result-jsrender").html(htmlJsrender);

// Insert the rendered (by Handlebars) HTML into the DOM.
$("#result-handlebars").html(htmlHandlebars);
<!-- Load jQuery -->
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha256-/SIrNqv8h6QGKDuNoLGA4iret+kyesCkHGzVUUV0shc=" crossorigin="anonymous"></script>

<!-- Load JsRender -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsrender/0.9.83/jsrender.min.js"></script>

<!-- Load Handlebars -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.min.js"></script>

<!-- JSRENDER ************************************************************ -->
<!-- Provide container for rendered jsRender template output: -->
<p><strong>jsRender output:</strong>
</p>
<div id="result-jsrender"></div>

<!-- Declare a JsRender template, in a script block: -->
<script id="subMenuTemplate" type="text/x-jsrender">
  <li class="menu__item{{if subMenu}} has-submenu{{/if}}">
    <a class="menu__link" {{if submenuName && subMenu}}data-submenu="{{:submenuName}}" {{/if}} href="#">{{:name}}</a>
    {{if subMenu}}
    <ul data-menu="{{:submenuName}}" class="menu__level">
      {{for subMenu tmpl='#subMenuTemplate'/}}
    </ul>
    {{/if}}
  </li>
</script>

<!-- Declare a JsRender template, in a script block: -->
<script id="entryPointTemplate" type="text/x-jsrender">
  <ul data-menu="main" class="menu__level">
    {{for data tmpl='#subMenuTemplate'/}}
  </ul>
</script>

<!-- HANDLEBARS ********************************************************** -->
<!-- Provide container for rendered Handlebars template output: -->
<p><strong>Handlebars output:</strong>
</p>
<div id="result-handlebars"></div>

<!-- Declare an Handlebars template, in a script block: -->
<script id="subMenuTemplate-handlebars" type="text/x-jsrender">
  <li class="menu__item{{#if subMenu}} has-submenu{{/if}}">
    <a class="menu__link" {{#if subMenu}}data-submenu="{{submenuName}}" {{/if}} href="#">{{name}}</a>
    {{#if subMenu}}
    <ul data-menu="{{submenuName}}" class="menu__level">
      {{#each subMenu}} {{> subMenuTemplate}} {{/each}}
    </ul>
    {{/if}}
  </li>
</script>

<!-- Declare an Handlebars template, in a script block: -->
<script id="entryPointTemplate-handlebars" type="text/x-handlebars-template">
  <ul data-menu="main" class="menu__level">
    {{#each data}} {{> subMenuTemplate}} {{/each}}
  </ul>
</script>