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>
添加回答
举报