我正在尝试为用户实现一种删除嵌套列表项的方法,从DOM中删除该项,然后删除除了被删除的LI之外没有其他子项的所有父项。如果用户尝试删除的LI具有子节点,我也不希望删除LI。我的javascript无法正常运行。它会删除所有父母,无论他们是否有孩子。
这是jsfiddle,我想要它,如果单击X,我想删除LI' 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 :(得分:0)
尝试使用
var containerEl = document.querySelector('#mainContainer');
var childrenArr = [];
for (var i = 0; i < containerEl.children.length; i++) {
childrenArr.push(containerEl.children[i]);
}
// Shuffle array
childrenArr.sort(function() {
return Math.random() - 0.5;
});
// Re-add shuffled children
for (var i = 0; i < childrenArr.length; i++) {
containerEl.appendChild(childrenArr[i])
}
而不是
$(this).parents('li');
$(this).parent('li');
答案 1 :(得分:0)
尝试使用
$('li').click(function(e) {
e.stopPropagation();
if($(this).find('ul').length == 0)
$(this).remove();
});
经过测试here