2013-03-05 75 views
1

我有一個子彈地區像從父刪除一個孩子,並將其作爲同級添加到父

  • 你好
  • 怎麼樣

不,我選擇

  • 和改變編號子彈。 所以我的名單應該像

    • 你好
    • 改變
    1. 怎麼樣

    1. 要結束第二個孩子後,光盤子彈。
    2. 想要添加第三個孩子作爲兄弟姐妹給父母。
    3. 想要再次將光盤子彈製作爲第四個孩子並將其作爲兄弟添加到父級。

    我該怎麼做。

    +0

    [你有什麼嘗試?](http://whathaveyoutried.com) – 2013-03-05 04:46:51

    +0

    [這樣的基本教程](http://www.echoecho.com/htmllists01.htm)應該是有幫助的 – AurA 2013-03-05 04:55:58

    +0

    我迭代節點和改變風格。但是我的節點就像是當前UL節點的子節點。我想結束當前UL節點,修改過的孩子必須被刪除並作爲兄弟姐妹插入當前的UL節點。 – 2013-03-05 05:02:54

    回答

    0

    這實際上是一個非平凡且非常有趣的問題。但是,您需要先了解幾件事情:

    1. 列表項目上的項目符號由其列表確定; ul用於無序列表(即磁盤項目符號),而ol用於有序列表(即編號項目符號)。
    2. 如果父母不是ulol,就不能有li
    3. 你不能有一個ulol反之亦然直接孩子(他們可以是li不過的孩子,但他們會子列表)

    這意味着,每次切換列表中,您需要確保您正在切換的項目具有正確(和相反)類型的父項,並且它之前和之後的項目也位於正確類型的(單獨)列表中。在很多情況下,您需要創建這些列表(或者在它們變空時刪除它們)。

    反正話是不值錢的,這裏的代碼(我使用jQuery,但這個想法應該是一樣的,不管你用什麼):

    $('li').on('click', function() { 
        var $listItem = $(this); 
        var $list  = $(this).parent(); 
        var $items = $list.children(); 
        var itemIndex = $items.index($listItem); 
        var numItems = $items.length; 
    
        var curType = $list.is('ul') ? 'ul' : 'ol'; 
        var newType = curType === 'ul' ? 'ol' : 'ul'; 
    
        var $prev = $list.prev(); 
        var $next = $list.next(); 
    
        if (itemIndex === 0) { 
         // The item we're switching is the first Item in the list 
         if (!$prev.is(newType)) { 
          $prev = $('<' + newType + '/>'); 
          $prev.insertBefore($list); 
         } 
         $prev.append($listItem); 
        } else if (itemIndex === numItems - 1) { 
         // The item we're switching is the last Item in the list 
         if (!$next.is(newType)) { 
          $next = $('<' + newType + '/>'); 
          $next.insertAfter($list); 
         } 
         $next.prepend($listItem); 
        } else { 
         // The item is in the middle, we need to split the current list into 3. 
         $tailList = $('<' + curType + '/>'); 
         $tailList.append($listItem.nextAll()); 
         $tailList.insertAfter($list); 
    
         $middleList = $('<' + newType + '/>'); 
         $middleList.append($listItem); 
         $middleList.insertAfter($list); 
        } 
    
        if (numItems === 1) { 
         // list used to have only one Item, so it's now empty, and should be removed. 
         $list.remove(); 
    
         if ($prev.is(newType) && $next.is(newType)) { 
          // The two surrounding lists are of the same type and should be merged. 
          $prev.append($next.children()); 
          $next.remove(); 
         } 
        } 
    }); 
    

    我使用一個click事件列表項來切換列表項。這裏有一個jsFiddle鏈接,可供玩家執行並驗證一切正常,如預期的那樣:http://jsfiddle.net/8Z9rf/

    該代碼絕對可以針對速度/性能進行優化,但我的目標是簡單明瞭,希望我能設法做到這一點。

    相關問題