调用Firebase数据库child()返回" undefined"在Javascript中

时间:2017-05-28 17:32:11

标签: javascript jquery html firebase firebase-realtime-database

这就是我所拥有的

Firebase数据库:

setores: {
    -KkBgUmX6BEeVyrudlfK: {
        id: '-KkBgUmX6BEeVyrudlfK',
        nome: 'test'
    }
    -KkDYxfwka8YM6uFOWpH: {
        id: '-KkDYxfwka8YM6uFOWpH',
        nome: 'test1'
    }
}

的JavaScript

var setorRef = firebase.database().ref().child("setores");
/* DELETE ROW */
$("#tbody_setores").on('click','.delete-btn', function(e){
    var $row = $(this).closest('tr'),
       rowId = $row.data('id');

    var rowId = $row.data('id');
    //it should remove the firebase object in here
    setorRef.child(rowId).remove()
    .then(function() {
      //after firebase confirmation, remove table row
      $row.remove();
    })
    .catch(function(error) {
      console.log('Synchronization failed');
    });  
});

setorRef.on("child_changed", snap => {

  var setorKey = snap.child("id").val();
  var nome = snap.child("nome").val();

  $("#tbody_setores").append("<tr data-id'"+setorKey+">"+
                                "<td class='mdl-data-table__cell--non-numeric'>" + nome + "</td>" +
                                "<td class='mdl-data-table__cell--non-numeric'>"+
                                  "<div buttons>"+
                                    "<button class='delete-btn mdl-button mdl-js-button mdl-button--icon mdl-button--colored'><i class='material-icons'>delete</i></button>"+" "+
                                  "</div>"+
                                "</td>"+
                              "</tr>");
});

现在,我想用这段代码做的是:当我点击附加在表上的删除按钮时,它应该删除数据库中的行和相应的对象。我在另一个表(here)上使用了相同的代码,它运行得很好,但在这一个上,rowId正在返回undefined而不是id。

1 个答案:

答案 0 :(得分:2)

您的HTML中似乎有一些拼写错误(在data-id属性中):

$("#tbody_setores").append("<tr data-id'"+setorKey+">"+

应该是这样读的:

$("#tbody_setores").append("<tr data-id='"+setorKey+"'>"+ 

这很好地解释了为什么rowId返回undefined而不是id;)