2 回答

TA貢獻1893條經驗 獲得超10個贊
this在您的 html onclick 屬性上添加參數,使其成為deleteFile(this)
然后在你的 js 上
function deleteFile(element){
var postId = $(element).closest('div').attr('id');
alert("You have selected id: " + postId);
var sure = confirm("Are you sure you want to delete this post?");
if(sure){
firebase.database().ref().child('Posts/' + postId).remove().then(function(){
alert("Post deleted sucessfully");
});
}
};

TA貢獻1775條經驗 獲得超11個贊
與 onclick 配對$(this)
不會像您預期的那樣工作,因為$(this)
有不同的上下文,您可以使用查看其值console.log($(this));
應該做的是向該按鈕添加一個類并通過 jquery 綁定一個 onclick 事件。運行下面的代碼片段。
紅色 div 包含通過 jquery 附加的 onclick 事件。
黃色 div 包含附加到按鈕屬性 onclick 的 onclick 事件。
$(document).ready(function(){
$(".getIdButton").click(function() {
alert($(this).closest("div").attr("id"));
});
});
function getId() {
alert($(this).closest("div").attr("id"));
console.log($(this));
}
div {
width: 100px;
height: 100px;
padding: 20px;
display: inline-block;
}
#red {
background-color: red;
}
#yellow {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="red">
<a href="#">Just a link</a>
<button class="getIdButton">Click Me</button>
</div>
<div id="yellow">
<a href="#">Just a link</a>
<button onclick="getId()">Click Me</button>
</div>
添加回答
舉報