<html>
<head>
<link href="./bootstrap.min.css" rel="stylesheet">
<script src="./jquery.js"></script>
<script type="text/javascript">
var data = [
{ id: 1, dept: '腾讯公司', remark: '这是总部', updeptid: 0 },
{ id: 2, dept: '中国分公司', remark: '分公司', updeptid: 1 },
{ id: 3, dept: '深圳分公司', remark: '这是总部', updeptid: 2 },
{ id: 4, dept: '开发一部', remark: '这是总部', updeptid: 3 },
{ id: 5, dept: '开发二部', remark: '这是总部', updeptid: 3 },
{ id: 6, dept: '财务部', remark: '这是总部', updeptid: 3 },
{ id: 7, dept: '上海分公司', remark: '这是分公司', updeptid: 2 },
{ id: 8, dept: '研发部', remark: '这是总部', updeptid: 7 }
];
$(function () {
$.each(data, function (index, item) {
var deep = (getDeep(item.updeptid, 0));
var haveChildren = containsChildren(item.id);
var id = '';
if(deep > 0){
for(var i =0;i< deep; i ++) {
id = id + ' ';
}
}
id = id + '<img src="./'+ (haveChildren ? '文件夹': '文件') +'.png"/>';
id = id + item.id;
var _html = '<tr status="show" tpid='+ item.updeptid +' tid='+ item.id +'><td '+ (haveChildren? ' class="parent"': '') +'>' + id + '</td><td>' + item.dept + '</td><td>' + item.remark + '</td></tr>';
$("#tb_dept tbody").append(_html);
})
$('#tb_dept tr').click(function(){
var id = ($(this).attr('tid'));
var status = ($(this).attr('status'));
$.each($('#tb_dept tr'), function(index, item){
if($(item).attr('tpid') == id) {
if(status == 'show')
$(item).hide();
else
$(item).show();
}
$('tr[tpid="'+ id +'"]').click();
})
$(this).attr('status', (status == 'show') ? 'hide': 'show');
})
})
function getDeep(updeptid, deep) {
for (var i = 0; i < data.length; i++) {
if(data[i]['id'] == updeptid) {
deep = deep + 1;
return getDeep(data[i]['updeptid'], deep);
break;
}
}
return deep;
}
function containsChildren(id){
for (var i = 0; i < data.length; i++) {
if(data[i]['updeptid'] == id) {
return true;
}
}
return false;
}
</script>
</head>
<body>
<table id="tb_dept" class="table">
<thead>
<th>ID</th>
<th>部门</th>
<th>备注</th>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>