js代码
var data = [{element:'图片',id:'1',pid:'0'},//count=1
{element:'大图片',id:'2',pid:'1'},
{element:'png',id:'3',pid:'2'},
{element:'jpeg',id:'4',pid:'2'},
{element:'gif',id:'5',pid:'2'},
{element:'gif11',id:'6',pid:'5'},
{element:'gif111',id:'7',pid:'6'},
{element:'gif222',id:'8',pid:'6'},
{element:'文字',id:'9',pid:'0'},
{element:'宋体',id:'10',pid:'9'},
{element:'宋体111',id:'11',pid:'10'},
{element:'宋体222',id:'12',pid:'10'},
{element:'黑体',id:'13',pid:'9'},];
function transTreeData(arr) {
if(arr.length) {
var pid = '0';
return findChild(pid, arr);
} else {
return [];
}
}
function findChild(pid, arr) {
var _arr = [];
for(var i=0; i<arr.length; i++) {
if(arr[i].pid == pid) {
var obj = arr[i];
obj.children = findChild(arr[i].id, arr);
_arr.push(obj);
}
}
return _arr;
}
function createDom (arr) {
var str = '<ul>';
for (var i=0; i < arr.length; i++) {
str+= `<li><input type="checkbox" id=${arr[i].id} value="" `+`/><label name=${arr[i].id}>`+ arr[i].element+`</label>`;
if(arr[i].children.length) {
str+=createDom(arr[i].children);
}
}
str += '</li></ul>';
return str;
}
$(document).ready(function(){
$('#treeContainer').html(createDom((transTreeData(data))));
$('#treeContainer').delegate('label', 'click', function() {
var id = $(this).attr('name');
$("#"+id).parent('li').find('input').prop({
checked: !($('#'+id).prop('checked'))
});
});
$('#treeContainer').delegate('input', 'change', function() {
var id = $(this).prop('id');
$("#"+id).parent('li').find('input').prop({
checked: $(this)[0].checked
});
});
$('#btn').click(function() {
const arr = [];
$(':checked').map(function(index, item) {
arr.push({
id: $(this).attr('id'),
})
})
console.log('------arr', arr);
})
});
HTML 代码
<code>
<div id="treeContainer"></div>
<button id="btn">提交</button>
</code>
网友评论