通过其相关钥匙删除孩子



因此,到目前为止,我有以下代码,但是,当单击"删除"按钮时,没有删除孩子。似乎从未触发点击函数,因为我尝试添加警报语句并且不起作用。

<table id="removeTable" class="mdl-data-table mdl-js-data-table mdl-shadow--2dp">
<thead>
<tr>
<th>Employee ID</th>
<th>Name</th>
<th>Email</th>
<th>Remove</th>
</tr>
</thead>
<tbody id="table_body"></tbody>
</table>
var rootRef = firebase.database().ref().child("Employees");
rootRef.on('child_added', snap => {
  var id = snap.child("ID").val();
  var key = snap.key;
  var name = snap.child("Name").val();
  var email = snap.child("Email").val();
  var btn = "<button key='"+ key +"' class='removeEmployee mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent'>Remove</button>";
  $("#table_body").append("<tr id='"+key+"'><td>" + id + "</td><td>" + name + "</td> <td>" + email +
                          "</td><td><button>" + btn +"</button></td></tr>");
});
$("#removeEmployee").click(
  function(){
    alert();
  }
);
// now this click handler can be (should be) moved outside 'child_added' callback
  $(".removeEmployee").click(function(){ // note: using 'removeElement' as class, not as id
    alert("clicked!");
    var key = $(this).attr('key');
    var itemToRemove = rootRef.child(key);
    itemToRemove.remove()
   .then(function() { // removed from Firebase DB
     console.log("Remove succeeded.")
   })
   .catch(function(error) {
     console.log("Remove failed: " + error.message)
   });
  });
// keeping this separate so that even if the item is removed by any other means (e.g.- directly from server console) this UI will remain in sync
rootRef.on('child_removed', function(snap) {
  var key = snap.key;
  $('#'+key).remove();
});

为什么不使用.on方法连接处理程序,以在'文档'的帮助下触发,并且只有当按钮存在时?

$(document).on('click', ".removeEmployee", function(){
  alert('My text : ' + $(this).text());
});

(顺便说一句,您正在尝试使用"#"选择按钮,该按钮用于选择元素ID。但是Remove Employeee是CSS类,因此您需要使用'.RemoveEmployee')

这是在元素之前创建的处理程序的演示:

console.log("Attaching handler");
setTimeout(function() {
  $(document).on('click', ".removeEmployee", function() {
    alert('My text : ' + $(this).text());
  });
  console.log("Creating the button");
  setTimeout(function() {
    $('#container').append('<button class="removeEmployee">Remove</button>');
    console.log("Ready for click!")
  }, 1000);
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>

您的问题与Firebase无关。

jQuery不会自动连接单击事件以动态创建的内容;您必须手动添加这些点击处理程序。创建新元素时最好完成。

// wrap in a jquery object
var btn = $("<button key='"+ key +"' class='removeEmployee mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent'>Remove</button>");
// then add a click event handler to it
btn.on('click', function() {
    var key = $(this).attr('key');
    alert("clicked! " + key);
});
// then add it to the table
$("#table_body").append("<tr id='"+key+"'><td>" + id + "</td><td>" + name + "</td> <td>" + email + "</td><td><button>" + btn +"</button></td></tr>");

最新更新