从无序列表

时间:2015-07-23 15:59:28

标签: javascript jquery

我有以下数据列表:

enter image description here

使用此HTML设置:

<ul id='tree'>
    <li data-id="1" data-parent="0">
        Home
        <ul>
            <li data-id="2" data-parent="1">
                About
                <ul>
                    <li data-id="4" data-parent="2">
                        What we do
                    </li>
                </ul>
            </li>

            <li data-id="3" data-parent="1">
                Contact
                <ul>
                    <li data-id="5" data-parent="3">
                        Employees
                        <ul>
                            <li data-id="6" data-parent="5">
                                Full-time
                            </li>

                            <li data-id="7" data-parent="5">
                                Part-time
                            </li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

单击按钮后,我想为每个列表项生成节点路径,并将其添加到我可以格式化的数据字符串中。

我从这开始:

$('button').on('click', function(){ 

    var output = "";

    $("ul#tree li").each(function(){
         var id = $(this).data("id");
         var parent = $(this).data("parent");
         output = output + "id=" + id + "&parent=" + parent + "$"; 
    });

    $("section").html(output);

});

生成:

id=1&parent=0
id=2&parent=1
id=4&parent=2
id=3&parent=1
id=5&parent=3
id=6&parent=5
id=7&parent=5

但是,我想添加每一行的节点路径(父ID的路径到当前列表项)。因此,例如,它看起来像这样:

id=1&parent=0&node_path=.0.
id=2&parent=1&node_path=.0.1.
id=4&parent=2&node_path=.0.1.2.
id=3&parent=1&node_path=.0.1.
id=5&parent=3&node_path=.0.1.3.
id=6&parent=5&node_path=.0.1.3.5.
id=7&parent=5&node_path=.0.1.3.5.

我不确定如何创建一个将父ID在ul&gt;路径中组合的函数。李的...

4 个答案:

答案 0 :(得分:2)

这样的东西?此示例拉取node7并沿树构建数据ID的路径。

&#13;
&#13;
var node7 = document.getElementById('node7');

alert( pathToNode(node7) );

function pathToNode(node) {
  var path = [];
  var parent = node.parentElement;
  while(parent && parent.id !== 'tree') {
    if( parent.dataset.id ){
      path.unshift(parent.dataset.id);
    }
    parent = parent.parentElement;
  }
  return path.join('.');
}
&#13;
<ul id='tree'>
    <li data-id="1" data-parent="0">
        Home
        <ul>
            <li data-id="2" data-parent="1">
                About
                <ul>
                    <li data-id="4" data-parent="2">
                        What we do
                    </li>
                </ul>
            </li>

            <li data-id="3" data-parent="1">
                Contact
                <ul>
                    <li data-id="5" data-parent="3">
                        Employees
                        <ul>
                            <li data-id="6" data-parent="5">
                                Full-time
                            </li>

                            <li data-id="7" id="node7" data-parent="5">
                                Part-time
                            </li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以查找所有列表项并通过上一步开始构建并继续重复,直到您点击ul#tree。继承人我会怎么做:

&#13;
&#13;
var all = {};
$('#tree li').each(function(){
    // Define a general i, a path variable, and the first parent
    var id = $(this).data('id') || false;
    var path = id;
    var parent = $(this).parent();
    // This will ignore any list items without an id.
    if(id){
        // While the parent is not ul#tree, keep going up.
        while(parent.attr('id') !== 'tree'){
            var t = parent.data('id') || false;
            // There are many ways to output your data.
            // I decided to wrap them in objects, that you can use in JS.
            // But you could off course build a string. Just rememeber that `t`
            // is the value that should _before_ the previous value, 
            // as its higher up the chain.
            if(t){
              var temp = {};
              temp[t] = path;
              path = temp
            }
            //path = t ? { + path : path;
            parent = parent.parent();
        }
        all[id] = path;
    }
});

console.log(all)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<ul id="tree">
 <li data-id="1">1</li> 
 <li data-id="2">
  <ul>
    <li data-id="5">1</li> 
    <li data-id="6">
      <ul>
        <li data-id="9">1</li> 
        <li data-id="10"></li> 
      </ul>
    </li> 
  </ul>
 </li> 
 <li data-id="3">1</li> 
 <li data-id="4">
  <ul>
    <li data-id="7">1</li> 
    <li data-id="8">1</li> 
  </ul>
</li> 
</ul>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以编写递归函数来跟踪父级,直到找不到父级,并返回路径。动态编程可以进一步节省跟踪时间。

  1. 检查其父li是否已被追踪。

  2. 如果跟踪父级,请获取父级路径,如果不跟踪,则直到满足root。

  3. 将父母的id放入结果路径,并存储以供进一步使用。

  4. $('button').on('click', function(){ 
    
            var output = "";
      
            // Keep the traced record, so we can reuse it, rather than tracing with the same route again.
            var store = {};
      
            var traceUp = function(id, pid) {
               var path = [];
               
               // If parent has already construct a path, just use it.
               if (typeof store[pid] !== 'undefined') {
                   path = store[pid].slice();
               } else {
                 // Otherwise, find the parent li, and keep traceup.
                 var pLi = $('li[data-id="' + pid +'"]');
                 if (pLi.length !== 0) {
                   path = path.concat(traceUp(pid, pLi.data('parent')));
                 }
               }
               path.push(pid);
               store[id] = path;
               return path;
            };
    
            $("ul#tree li").each(function(){
                 var id = $(this).data("id");
                 var parent = $(this).data("parent");
                 // Get the trace result in an array.
                 var path = traceUp(id, parent);
                 
                 // use .join to convert array to string with desired format.
                 output = output + "id=" + id + "&parent=" + parent + "&path=." + path.join('.') + '<br/>'; 
            });
    
            $("section").html(output);
    
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <ul id='tree'>
        <li data-id="1" data-parent="0">
            Home
            <ul>
                <li data-id="2" data-parent="1">
                    About
                    <ul>
                        <li data-id="4" data-parent="2">
                            What we do
                        </li>
                    </ul>
                </li>
    
                <li data-id="3" data-parent="1">
                    Contact
                    <ul>
                        <li data-id="5" data-parent="3">
                            Employees
                            <ul>
                                <li data-id="6" data-parent="5">
                                    Full-time
                                </li>
    
                                <li data-id="7" data-parent="5">
                                    Part-time
                                </li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>
    <button>click</button>
    <section></section>

答案 3 :(得分:1)

您可以使用parents()获取父母列表。你可以更进一步,一起摆脱父数据属性,这将简化以下代码。

$('#mybutton').on('click', function () {

     var output = "";

     $("ul#tree li").each(function () {
         var id = $(this).data("id");
         var parent = $(this).data("parent");
         output = output + "id=" + id + "&parent=" + parent  + "&node_path=";

         var node_path = parent + ".";
         $(this).parents('li').each(function() {
             node_path +=  $(this).data("parent") + ".";
         });
         output += node_path.split('').reverse().join('')
         output += "<br/>";
     });

     $("#mysection").html(output);

 });

http://jsfiddle.net/4t6jgzhu/