2011-03-11 7 views
6

en JavaScript, tengo una serie de objetos que representa una lista de profundidad arbitraria ...usar jQuery para generar una lista de profundidad arbitraria

data = 
[ 
{ title, depth }, 
{ title, depth }, 
{ title, depth }, 
{ title, depth }, 
] 

... donde la profundidad es la profundidad en la lista es el elemento .

Quiero convertir estos datos en html.

Por ejemplo:

[ 
{ title: "one", depth : 1 }, 
{ title: "two", depth : 1 }, 
{ title: "three", depth : 2 }, 
{ title: "four", depth : 3 }, 
{ title: "five", depth : 1 }, 
] 

se convierte ...

<ul> 
    <li><p>one</p></li> 
    <li> 
    <p>two</p> 
    <ul> 
     <li> 
     <p>three</p> 
     <ul> 
      <li><p>four</p></li> 
     </ul> 
     </li> 
    </ul> 
    </li> 
    <li><p>five</p></li> 
</ul> 

¿Cuál es la forma más sencilla de hacer esto, usando jQuery?

Gracias

+0

¿Es necesario que el orden se mantiene? ¿O puede ser así?

  • uno

  • cinco

  • dos

    • tres

      • cuatro

Respuesta

7

Esta es una manera que podría hacerlo:

(function($) { 
    $.listify = function(items) { 
    var container = $('<div></div>'), root = container; 
    var depth = 0; 
    for (var i = 0; i < items.length; ++i) { 
     var item = items[i]; 
     if (item.depth > depth) { 
     while (item.depth > depth) { 
      var ul = $('<ul></ul>').appendTo(container); 
      var li = $('<li></li>').appendTo(ul); 
      container = li; 
      ++depth; 
     } 
     } else if (item.depth <= depth) { 
     while (item.depth < depth) { 
      container = container.parent().parent(); 
      --depth; 
     } 
     container = $('<li></li>').insertAfter(container); 
     } 
     container.append('<p>' + item.title + '</p>'); 
    } 
    return root.children(); 
    } 
})(jQuery); 

admito, yo sólo quería nombrar algo listify. Here is a jsFiddle. ustedes lo llaman así:

$.listify([ 
    { title: "one", depth : 1 }, 
    { title: "two", depth : 1 }, 
    { title: "three", depth : 2 }, 
    { title: "four", depth : 3 }, 
    { title: "five", depth : 1 }, 
]).appendTo(document.body); 
+1

Muy bueno, gracias. Merece puntos de bonificación por nombrarlo 'listify'. – trev

1

Ésta es dinámica:

http://jsfiddle.net/wq8QY/

no importa cuántos niveles hay que bajar todavía se creará todo el camino.

var json = [ 
{ title: "one", depth : 1 }, 
{ title: "two", depth : 10 }, 
{ title: "three", depth : 20 }, 
{ title: "four", depth : 25 }, 
{ title: "five", depth : 11 }, 
] 
    var dom = $('body') ; 
    dom.append($('<ul>')) 
    //console.log(json.length) 
    for(var i = 0; i < json.length; i++){ 
    //console.log(json[i]) 
     var appendTo = $('body') 
     for(var j = 1; j <= json[i].depth; j++){ 
      console.log(appendTo, json[i], json[i].depth, '1st') 
      if(appendTo.children('ul').length <= 0){ 
       console.log('no ul', j) 
       appendTo.append($('<ul>')) 
      } 
      appendTo = $(appendTo.children('ul')) 
      console.log(appendTo, json[i], '2nd') 
     } 
     console.log(appendTo, json[i], 'appending') 
     appendTo.append($('<li><p>'+json[i].title+'</p></li>')) 
    } 
0
$.fn.listify = function(list) { 
    var stack = [this]; 
    $.each(list, function() { 
     var item = $('<li><p>'+this.title+'</p></li>'); 
     stack[this.depth] = stack[this.depth] 
      ? item.insertAfter(stack[this.depth]) 
      : item.wrap('<ul>').appendTo(stack[this.depth - 1]); 
     stack.length = this.depth + 1; 
    }); 
} 
3

Obras con múltiples niveles y correctamente los nidos de los tags:

(function ($) { 
    $.makelist = function (arr) { 
    var currentdepth = 1; 
    var root = $('<ul>'); 
    var el = root; 
    var idx = 0; 

    while (idx < arr.length) { 
     if (arr[idx].depth == currentdepth) { 
     el.append($('<li>').html($('<p>').text(arr[idx].title))); 
     idx++; 
     } 
     else if (arr[idx].depth > currentdepth) { 
     newel = $('<ul>'); 
     el.append(newel); 
     el = newel; 
     currentdepth++; 
     } 
     else { 
     el = el.parent('ul'); 
     currentdepth--; 
     } 
    } 
    return root; 
    } 
})(jQuery); 

     $(document).ready(function() { 
      arr = [ 
        { title: "one", depth: 1 }, 
        { title: "two", depth: 1 }, 
        { title: "three", depth: 2 }, 
        { title: "four", depth: 3 }, 
        { title: "five", depth: 1 }, 
        ]; 

      $('body').append($.makelist(arr)); 
     }); 
Cuestiones relacionadas