我在here之前问了一个问题,我一直在检查相同的代码。我不知道如何使用prevChildKey删除项目。
控制台错误给出以下提示:
未捕获的ReferenceError:未定义deleteData 在HTMLButtonElement.onclick(index.html:1)
index.html
<div id="list_div" class="list-div">
</div>
index.js
// Database Reference
var DataRef = firebase.database().ref('users/' + currentUser.uid + '/exercises/');
// Read data from database
function readData(){
//var readDataRef = firebase.database().ref('users/' + currentUser.uid + '/exercises/');
DataRef.on("child_added", function(data, prevChildKey) {
var newData = data.val();
console.log("ID: " + prevChildKey);
console.log("name: " + newData.name);
console.log("sets: " + newData.sets);
console.log("reps: " + newData.reps);
console.log("weights: " + newData.weights);
document.getElementById("list_div").innerHTML+=`
<div id="listitem_div" class="listitem-div">
<span class="listtext">Exercise Name: </span>${newData.name}<br>
<span class="listtext">Set: </span>${newData.sets}
<span class="listtext">Reps: </span>${newData.reps}
<span class="listtext">Weights: </span>${newData.weights}
<button type="submit" id="itemremove" class="itemremove" onclick="deleteData(${prevChildKey})">Delete</button>
</div>
`
});
}
//Delete data from database
function deleteData(prevChildKey){
var newDataRef = firebase.database().ref('users/' + currentUser.uid + 'exercises/' + prevChildKey);
newDataRef.remove()
}
答案 0 :(得分:1)
您收到的prevChildKey
不是要删除的练习的键。
请改为使用data.key
来获取练习的ID,并在其上调用remove。
console.log("ID: " + data.key);