我有一个表格和一个类别页面,这些类别可以保存文档。我的类别索引页面显示了我的所有类别,并且可以选择删除我想要的类别。我只是希望能够排除该类别没有任何文档的情况。
我的结构是:
我的代码中删除类别的部分是这样的:
$('.exclude i').click(function(){
if(categoriasRef.child($(this).parent().attr('keyCategoria')).child('documentos')){
if(confirm("Você realmente deseja apagar esse registro?")){
categoriasRef.child($(this).parent().attr('keyCategoria')).remove();
}
}
})
我尝试添加:
if(categoriasRef.child($(this).parent().attr('keyCategoria')).child('documentos'))
,但即使该类别没有像您的 child 这样的文档,这个条件也总是正确的,因此该条件总是成立,您可以删除该类别。
我不知道如何区分带文档和不带文档的类别,以便对有文档且无法删除的类别进行处理。
为了更好地理解整个代码:
function initFirebase(){
function carregaCategorias(){
categoriasRef.on('value', function(data){
headertb = isAdmin ? "<th>Categoria</th><th>Editar</th><th>Excluir</th>" : "<th>Categoria</th>";
$('#tableCustom thead tr').html(headertb);
$("#tableCustom").dataTable().fnDestroy();
$('#tableCustom tbody').html('');
for(var key in data.val()){
categoria = data.val()[key]
if(isAdmin){
linha = "<tr>"+
"<td>"+categoria.titulo+"</td>"+
"<td><a href='/categorias/"+key+"/edit/'><i class='fa fa-edit'></i></a></td>"+
"<td class='exclude' keyCategoria='"+key+"'><i class='fa fa-trash-o'></i></td>"+
"</tr>";
$('#tableCustom').append(linha);
}else{
window.location = "/documentos?estado=not_admin";
}
}
closeLoader();
//datatable
$('#tableCustom').dataTable({
"aaSorting": [[ 0, "asc" ]],
"oLanguage": {
"sUrl": "/datatable_pt.txt"
},
"aoColumnDefs": [
{ "bSortable": true, "aTargets": [ 0 ] },
{ "bSearchable": false, "aTargets": [ 0 ] }
]
});
if(isAdmin){
$('.exclude i').click(function(){
if(categoriasRef.child($(this).parent().attr('keyCategoria')).child('documentos')){
if(confirm("Você realmente deseja apagar esse registro?")){
categoriasRef.child($(this).parent().attr('keyCategoria')).remove();
}
}
})
}
});
}
carregaCategorias();
}
最佳答案
您尝试过使用存在吗?
关于javascript - Firebase - 检查数据是否有子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48064614/