我有一個樹ul
並具有以下結構:jQuery的無法刪除列表中的元素
<div id="Tree">
<ul>
<li>
<a class="collapseLink" href="#">
<span class="hide">Expand Root Node</span>
</a>
<a class="selectLink" href="#">
Root Node
</a>
<ul>
<li id="item_1">Sub Node 1</li>
<li id="item_2">Sub Node 2</li>
<li id="item_3">Sub Node 3</li>
<li id="item_4">Sub Node 4</li>
<li id="item_5">Sub Node 5</li>
<li id="item_6">Sub Node 6</li>
</ul>
</li>
</ul>
</div>
我會非常想限制在樹中的子節點的數量,並試圖用以下代碼實現:
$(document).ready(function() {
var rootNode = $('#Tree ul li a:first');
// If the root node has an 'expandLink' class then it's closed and can be opened //(via a click)
if (rootNode.hasClass('expandLink')){
rootNode.click();
limitRootNodes();
}
function limitRootNodes() {
// Get the direct child nodes for the root list element
var tree_ul = $('#Tree ul li ul:first').children();
// list limit
var max_listCount = 3;
// remove the last element if the list size exceeds the limit
while (tree_ul.size() > max_listCount){
$('li:last-child', tree_ul).remove();
}
}
});
但是,上面的代碼並沒有刪除多餘的列表元素。有什麼建議是什麼導致這個?
感謝John對您的及時貢獻。但是,根據建議更改屬性不起作用。我想相信也許我打電話的方法是錯誤的? – chridam 2009-06-12 15:02:40
T B指出了我的錯誤。我已經將其更新爲包含filter()函數,這可能是最簡單的方法。 – 2009-06-12 15:04:25
+1我將您的過濾器()解決方案添加到我的代碼中。 – 2009-06-12 15:17:35