2011-10-21 45 views
2

我有一個由ajax填充的嵌套無序列表,我正在尋找創建麪包屑式導航。最終的結果應該是我點擊列表中的任何節點,父列表項顯示在麪包屑導航中。使用jQuery將嵌套無序列表轉換爲麪包屑

<div id="list"> 
    <ul> 
     <li class="expanded"> 
      <a href="#" id="1122">Root Group</a> 
     </li> 
     <ul> 
      <li class="expanded"> 
       <a href="#" id="1126">Northeast US</a> 
      </li> 
      <ul> 
       <li class="collapsed"> 
        <a href="#" id="1127">Massachusetts</a> 
       </li> 
       <ul style="display: none; "> 
        <li class="expanded node"> 
         <a href="#" id="1128">Mansfield-Foxboro</a> 
        </li> 
        <li class="expanded node"> 
         <a href="#" id="1129">North Attleboro</a> 
        </li> 
       </ul> 
       <li class="expanded"> 
        <a href="#" id="1144">New Hampshire</a> 
       </li> 
       <ul> 
        <li class="expanded node"> 
         <a href="#" id="1145">Manchester</a> 
        </li> 
       </ul> 
      </ul> 
      <li class="expanded"> 
       <a href="#" id="1181">Mid-Atlantic US</a> 
      </li> 
      <ul> 
       <li class="expanded"> 
        <a href="#" id="1182">New York City</a> 
       </li> 
       <ul> 
        <li class="expanded node"> 
         <a href="#" id="1183">Time Square</a> 
        </li> 
       </ul> 
      </ul> 
     </ul> 
    </ul> 
</div> 

所以我點擊紐約市,我也得到: 根集團>中大西洋美國>紐約

我點擊北阿特爾伯勒和獲取: 根集團>美國東北部>馬薩諸塞州> North Attleboro

有沒有一種方法可以使用jQuery遍歷構建此路徑?

回答

2

您可以從點擊<a>元素開始,用parents()以匹配其祖先鏈的<ul>元素,然後應用prev()到結果得到前面的<li>元素。

從那裏,您可以使用find()來匹配列表項中的<a>元素。如果你add()點擊超鏈接本身的結果集,你將有一個jQuery對象包含路徑中的所有超鏈接,按照正確的順序。

現在,您只需使用map()即可從<a>元素中構建一個內部文本值數組,以及Array.join()以連接路徑字符串。最終結果如下:

$("a").click(function() { 
    var path = $(this).parents("ul").prev("li").find("a").add(this) 
     .map(function() { 
      return $(this).text(); 
     }).get().join(" > "); 

    // Do something with 'path'... 
}); 

您可以在this fiddle中測試它。

+0

這是完美的 - 我不想引入任何不必要的標記,這找到確切的集合,而不依賴於.node類兩種。謝謝! – saranicole

0

你可以用下面的代碼的點擊<li>的所有<li>上代:

$('li').bind('click', function() { 
    var $ascendants = $(this).parents('ul'), 
     output  = []; 
    $.each($ascendants, function (index, value) { 
     output.push($(value).children('li').not('.node').children('a:first').text()); 
    }); 
    //output is not an array of all the text within parent li tags of the clicked li tag 
    console.log(output); 
}); 

此找到所有方興未艾<li><ul>標籤被點擊,通過他們的迭代,選擇從文本非.node<li>'s。

這裏是輸出,你可以使用你的breadcrums一個數組的jsfiddle:http://jsfiddle.net/rE9x8/1/

0

我只是粗略地導航結構:

$('a').click(function(e){ 
    e.preventDefault(); 
    for (var current = $(this),string = [];current.parent().parent().parent().attr('id') != 'list';current = current.parent().parent().prev().children('a')) 
     string.push(current.text()); 
    string.push(current.text()); 
    alert(string.reverse().join('>')); 
});