![](/img/trans.png)
[英]How to convert Html ul/ol list to tree liked data structure with javascript?
[英]how to grow the ul and ol list elements of a tree using javascript
我必須制作一棵樹,使其僅通過單擊就可以動態生成列表。
o 1
o 2
o 3
如果在此情況下,我單擊1,則應該創建一個子節點,可能是11。再次單擊1可能會創建一個22。
o 1
o 11
o 22
o 2
o 3
我將在該元素上單擊幾次,重復此過程。 一種情況可能是這樣的。
o 1
o 11
o 111
o 222
o 333
o 22
o 33
o 111
o 222
o 333
我完全不了解jquery框架,因為我從來沒有從事過該語法的工作,我了解到有關javascript的知識也太少了。 您能在這個方向上指導我以便我可以融入這樣的項目中嗎?
我必須生成基於知識的幫助模塊,該模塊包含幾個文件夾列表,該列表本身包含文件夾,每個文件夾都有要顯示給代理的數據。
對於前
folder1
folder1.1
folder1.2
folder1.3
folder1.4
folder1.4.1
folder1.4.2
folder1.4.3
folder1.5
該結構將使用樹數據結構顯示,每個文件夾都包含數據。 此文件夾結構將增長/可以動態增長。
不知道這對任何人有什么用,但是下面是一個逐步注釋的版本:
function foo(e) {
// Create a new LI
var newLi = document.createElement('li');
// Get the element that the click came from
var el = e.target || e.srcElement;
// Get it's parent LI if there is one
var p = getParent(el);
if (!p) return;
// Get child ULs if there are any
var ul = p.getElementsByTagName('ul')[0];
// If there's a child UL, add the LI with updated text
if (ul) {
// Get the li children ** Original commented line was buggy
// var lis = ul.getElementsByTagName('li');
var lis = ul.childNodes;
// Get the text of the last li
var text = getText(lis[lis.length - 1]);
// Update the innerText of the new LI and add it
setText(newLi, text.replace(/\.\d+$/,'.' + lis.length));
ul.appendChild(newLi);
// Otherwise, add a UL and LI
} else {
// Create a UL
ul = document.createElement('ul');
// Add text to the new LI
setText(newLi, getText(p) + '.0');
// Append the new LI to the new UL
ul.appendChild(newLi);
// Add the UL
p.appendChild(ul);
}
function getParent(el) {
var tagName;
while (el) {
tagName = el.tagName.toLowerCase()
if (tagName == 'li') {
return el;
} else if (tagName == 'ul') {
return;
}
el = el.parentNode;
}
}
function getText(el) {
return el.textContent || el.innerText;
}
function setText(el, text) {
if (typeof el.textContent == 'string') {
el.textContent = text;
} else if (typeof el.innerText == 'string') {
el.innerText = text;
} else {
el.innerHTML = '';
el.appendChild(document.createTextNode(text));
}
}
}
一些使它起作用的HTML:
<ul onclick="foo(event)">
<li>0</li>
<li>1</li>
<li>2</li>
</ul>
在Safari 5.1.5,Firefox 3.5.6,IE 6中進行了測試,因此幾乎可以在任何地方使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.