从JSON对象动态创建无序列表。
function renderList(branches) {
var ul = document.createElement("ul");
for (var i=0, n=branches.length; i<n; i++) {
var branch = branches[i];
var li = document.createElement("li");
var text = document.createTextNode(branch.name);
li.appendChild(text);
if (branch.branches) {
li.appendChild(renderList(branch.branches));
}
ul.appendChild(li);
}
return ul;
}
function renderTree()
{
var treeRoot = document.getElementById("tree");
var treeObj = {"root":
[{
"name": "File",
"branches":[
{"name": "New"},
{"name": "Save"},
{"name": "Exit"}
]
}]
};
treeRoot.appendChild(renderList(treeObj.root));
}
json&amp; amp; javascript动态地将锚点添加到列表中?
动态从<li> File </li>
到<li> <a href="yahoo.com"> File </a> <li>
答案 0 :(得分:2)
将第text
行中的li.appendChild(text);
替换为锚节点:
function renderList(branches) {
var ul = document.createElement("ul");
for (var i=0, n=branches.length; i<n; i++) {
var branch = branches[i];
var li = document.createElement("li");
var text = document.createTextNode(branch.name);
// new code here
var a = document.createElement("a");
a.setAttribute('href', 'http://yahoo.com')
a.appendChild( text );
//
li.appendChild( a );
...
您的网址存储在哪里? (您可以更新上面的代码,将硬编码的网址替换为实际值,如果您将其存储在某处。)