所以到目前为止我有以下代码,但是,当单击删除按钮时,不会删除子项。似乎从未触发click函数,因为我尝试添加一个警告语句但它不起作用。
<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();
});
答案 0 :(得分:1)
为什么不使用http://www.drupal-8.dd:8083/install.php方法附加处理程序,在“文档”的帮助下触发,并且只有按钮存在?
$(document).on('click', ".removeEmployee", function(){
alert('My text : ' + $(this).text());
});
(顺便说一句,你试图选择带有'#'的按钮,用于按元素id选择。但是removeEmployee是一个css类,所以你需要使用'.removeEmployee') < / p>
以下是在元素之前创建的处理程序的演示:
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>
答案 1 :(得分:0)
您的问题与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>");