使用JavaScript从firebase中删除对象

时间:2017-05-16 00:20:21

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

我在firebase-database上设置一些对象,并在带有'child_added'和append()的HTML表格上显示它们,以便在它们添加到数据库后立即动态添加它们,并且必须有一个删除按钮在表的每一行,但问题是,我无法让这个删除按钮工作...

这就是数据库结构的样子:

Assets: {
    -KkBgUmX6BEeVyrudlfK: {
        id: '-KkBgUmX6BEeVyrudlfK',
        name: 'John',
        brand: 'HP'
    }
    -KkDYxfwka8YM6uFOWpH: {
        id: '-KkDYxfwka8YM6uFOWpH',
        name: 'Jack',
        brand: 'Dell'
    }
}

这是我的index.js

var rootRef = firebase.database().ref().child("Assets");
$("#table_body").on('click','.delete-btn', function(e){
    var $row = $(this).closest('tr'),
       rowId = $row.data('id');
    var assetKey = rootRef.child("id");
    //it should remove the firebase object in here
    rootRef.child(assetKey).remove()
    //after firebase confirmation, remove table row
    .then(function() {
      $row.remove();
    })
    //Catch errors
    .catch(function(error) {
      console.log('ERROR');
    });  
});

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

  var assetKey = snap.child("id").val();
  var name = snap.child("name").val();
  var brand = snap.child("brand").val();

$("#table_body").append("<tr data-id='"+assetKey+"'>"+
                          "<td>" + name + "</td>" +
                          "<td>" + brand + "</td>" +

                          "<td><div buttons>"+
                                  "<button class='delete-btn>delete</button>"+
                                  "</div></td></tr>");
});

assetKey内的rootRef.on("child_changed", snap => {如果在console.log上显示,则返回对象键的正确值,但$("#table_body").on('click','.delete-btn', function(e){上的'assetKey'无法正常工作...

1 个答案:

答案 0 :(得分:2)

这行看起来不对(尝试获取顶级id节点的不存在的Assets属性):

var assetKey = rootRef.child("id");

请改为尝试:

var rowId = $row.data('id');
rootRef.child(rowId).remove()
...