2015-12-03 87 views
-1

我想實現一種方式讓用戶刪除一個嵌套列表項,從DOM中刪除該項,然後刪除所有父母除了LI被移除之外,沒有額外的孩子。如果用戶試圖刪除的那個孩子有孩子,我也不希望那個LI被刪除。我的JavaScript無法正常工作。它會刪除所有家長,不管他們是否有孩子。只有當父母沒有額外的孩子時,才能刪除嵌套LI的父母

這裏是的jsfiddle,我想它,這樣如果單擊X,我想刪除了李的「d」和「C」,讓「B」和「E」完整: jsfiddle.net/2t0xrv8c/2

我的JavaScript:

$(document).on('click', '.delete-from-heading', function() { 
    var articleId = $(this).closest('.c-cont').attr("data-article"); 
    var crumbId = $(this).closest('li').attr("heading"); 

    //if the current LI doesn't have children, let's delete it, along with all parents that don't have children 
    if(!$(this).closest('li').children('li').length){ 
     $(this).closest('li').removeClass('assigned');   

     //for each parent li 
     $(this).parents('li').each(function(index) { 
      // check to see if it has children LI's   
      if(!$(this).children('li').length){ 
       $(this).remove(); 
      } 
      $(this).remove(); 
     }); 

    }else{ 
     //The current LI has children, so let's just remove the delete button 
     $(this).closest('li').removeClass('assigned'); 
     $(this).remove();   
    } 
}); 

我的HTML:

<div class="crumb-cont" tree="0"><h5>NOTES</h5> 
     <ul> 
      <li heading="40845" parent="0"> 
       <div class="">METHODS </div> 
       <ul> 
        <li heading="41896" parent="40845"> 
         <div class="">Immune cell types</div> 
       <ul> 
        <li heading="41356" parent="41896" class="assigned"> 
         <div>1. B cell analyses ***KEEPER review of this section done<span class="delete-from-heading tooltip-top" title="Remove article from this heading"></span></div> 
         <ul> 
          <li heading="41358" parent="41356"> 
            <div>Assays using different in vitro methods of manipulating B cells</div> 
            <ul> 
             <li heading="41360" parent="41358" class="assigned"> 
              <div>Combination of methods or applicable to multiple methods<span class="delete-from-heading tooltip-top" title="Remove article from this heading"></span></div> 
             </li> 
            </ul> 
           </li> 
          </ul> 
         </li> 
        </ul> 
      </li> 
     </ul> 
    </div> 
+0

您的描述是一團糟!請清楚。 – void

+0

HTML片段.......... –

+0

你可以在jsfiddle中添加你的代碼嗎? –

回答

0

嘗試使用

$(this).parents('li'); 
$(this).parent('li'); 

代替

$(this).closest('li') 
0

嘗試使用

$('li').click(function(e) { 
    e.stopPropagation(); 
if($(this).find('ul').length == 0) 
    $(this).remove(); 
}); 

測試它here

+0

我用我的代碼更新了jsfiddle。 jsfiddle.net/2t0xrv8c/2我想要它,所以如果X被點擊,LI的'd'和'c'被刪除,'b'和'e'保持不變。 – skiindude22

相關問題