onclick = “LoadXml(0)” / ><div id = “root” > </div>
</form >
</body>
前台代码:
<script type=”text/javascript”>
var object1 = null;
function LoadXml(id) {
$.ajax({
type: ”
post “,
url:”
WebForm1.aspx ? parentID = “+id,
dataType:”
xml “,
success: createTree
});
}
// 思路是每个父节点产生一个ul孩子并且ajax读取该父亲的直接儿子,拼接树
function createTree(xml) {
var obj = object1 == null ? (“#root “) : (object1);//判断是不是第一次加载,如果第一次加载则是最外的div的id,否则是父节点
$(obj).append(” < UL class = ‘ULfather’ > “);//添加ul对象
$(xml).find(”
value “).each(function() {//从xml里读出所有value节点信息,得到当前层次节点
//拼接<li>和<a>,属性通过xml中的value节点的属性id和节点文本进行拼接
$(obj).children(“.ULfather “).append(” < li > <a id = ” + $(this).attr(”
id “) + ” > ” + $(this).text() + ” < /a></li > “);
var alink = “#” + $(this).attr(”
id “); //得到当前超链接对象
$(alink).bind(”
click “, function() { //超连接绑定点击事件
if ($(alink + ” + ul “).size() <= 0) {//如果数据已经绑定则无需再次绑定,(如果超链接下个元素是ul的话,说明数据已经绑过)
object1 = $(alink).parent(”
li “);
LoadXml($(this).attr(”
id “))
}
else {
GetDisplayOrNot($(alink));
}
});
});
}
//节点显示或影藏
function GetDisplayOrNot(obj) {
if ($(obj).parent(”
li “).children(”
ul “).is(“: hidden “)) {
$(obj).parent(”
li “).children(”
ul “).css(”
display “, ”
block “);
}
else {
$(obj).parent(”
li “).children(”
ul “).css(”
display “, ”
none “);
}
}
</script>
后台:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq;
using System.Xml;
using System.Xml.Linq;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int id =Convert.ToInt32(Request[“parentID”]);
GetXML(id);
}
public IList<Product> GetList()
{
return new List<Product>()
{
new Product(){ Id=1, ParentId=0, HasChild=1, Name=”aaaaa” },
new Product(){ Id=2, ParentId=1, HasChild=1, Name=”bbbb1″ },










