我有一个像这样的无序列表。
<ul class="simpleTree">
<li>
<span>root</span>
<ul>
<li >
<span>Tree Node 1</span>
<ul>
<li>
<span>Tree Node 1-1</span>
<ul>
<li>
<span>Tree Node Ajax 1</span>
</li>
<li>
<span>Tree Node Ajax 2</span>
</li>
</ul>
</li>
<li>
<span>Tree Node 1-1</span>
<ul>
<li>
<span>Tree Node Ajax 1</span>
</li>
<li>
<span>Tree Node Ajax 2</span>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
我想把它改造成
<ul class="simpleTree">
<li class="root">
<span>
<a href="#"title="root">root</a</span> <ul> <li class="open">
<span><a href="test.html" title="this is the title">Tree Node 1</a></span>
<ul>
<li><span>Tree Node 1-1</span> <ul> <li>
<span class="text"><a href="test.html" title="this is the title">Tree Node Ajax 1</a></span>
</li> <li>
<span class="text"><a href="test2.html" title="this is the title for the second page">Tree Node Ajax 2</a></span>
</li> </ul>
</li>
<li><span>Tree Node 1-1</span>
<ul>
<li><span class="text"><a href="test.html" title="this is the title">Tree Node Ajax 1</a></span>
</li> <li>
<span class="text"><a href="test2.html" title="this is the title for the second page">Tree Node Ajax 2</a></span>
</li> </ul> </li> </ul>
</li>
</ul>
</li>
</ul>
以上格式通过循环遍历每个“li”元素并分配一个 css 类、 anchor 标记等,以编程方式使用 asp.net/C# 或 jquery。上面的无序列表只是一个示例。基本上我正在检索大约 600 条记录从数据库中提取并将它们转换为无序列表。有人可以建议我该怎么做吗?
更新:
我在 asp.net codebehind 中使用以下代码从数据库记录生成无序列表。
int lastDepth = -1;
int numUL = 0;
StringBuilder output = new StringBuilder();
foreach (DataRow row in ds.Tables[0].Rows)
{
int currentDepth = Convert.ToInt32(row["Depth"]);
if (lastDepth < currentDepth)
{
if (currentDepth == 0)
output.Append("<ul class=\"simpleTree\">");
else
output.Append("<ul>");
numUL++;
}
else if (lastDepth > currentDepth)
{
output.Append("</li></ul></li>");
numUL--;
}
else if (lastDepth > -1)
{
output.Append("</li>");
}
output.AppendFormat("<li><span>{0}</span>", row["name"]);
lastDepth = currentDepth;
}
for (int i = 1; i <= numUL; i++)
{
output.Append("</li></ul>");
}
literal1.text=output.ToString();
在我的数据库表中,我有名称、深度字段。使用“深度”字段,我将数据绑定(bind)到无序列表
提前致谢。
最佳答案
JavaScript:
您可以使用 DOMObject.innerHTML 读/写属性。或者,jQuery 的 .append()。
对于属性,DOMObject.setAttribute() 应该可以帮助您。
查看 this piece of jQuery documentation和 this .
我是否缺少您想要的某些功能?
关于html - 以编程方式将 CSSClass 分配给无序列表中的每个 li 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2361561/