2 回答
TA贡献1789条经验 获得超8个赞
的值onclick
应该是一个函数,您在进行赋值时调用该函数。
trash.onclick = function() { del(this) };
另外,thisDiv
是本地的displayPost()
,你不能在 中使用它del()
。你需要使用x.parentElement
.
您在 中还有很多其他拼写错误和小错误del()
,请参阅下面的更正。
function displayPost() {
var thisDiv = document.getElementById("posts");
var theDate = document.createElement("P");
theDate.classList.add("post-date");
var trash = document.createElement("BUTTON");
trash.classList.add("post-trash");
trash.innerHTML = '<i class="fa fa-window-close" aria-hidden="true"></i>';
thisDiv.appendChild(theDate);
thisDiv.appendChild(trash);
theDate.innerHTML = new Date();
trash.onclick = function() {del(this);};
}
function del(x){
var delTrash = document.getElementsByClassName("post-trash");
var delDate = document.getElementsByClassName("post-date");
var thisDiv = x.parentElement;
var index = Array.from(delTrash).indexOf(x);
thisDiv.removeChild(delTrash[index]);
thisDiv.removeChild(delDate[index]);
}
<div id="posts">
</div>
<button onclick="displayPost()">Add post</button>
TA贡献1797条经验 获得超4个赞
如果我答对了你的问题,这可能会对你有帮助。
<div class="container">
<!-- some posts with delete button -->
<div class="post">
Post One
<button class="delete-post">Delete Post</button>
</div>
<div class="post">
Post Two
<button class="delete-post">Delete Post</button>
</div>
<div class="post">
Post Three
<button class="delete-post">Delete Post</button>
</div>
</div>
<script>
window.onload = () => {
let postsDelBtn = document.getElementsByClassName("delete-post");
console.log(postsDelBtn)
for(let i = 0; i < postsDelBtn.length; i++){
postsDelBtn[i].addEventListener('click', (event) => {
event.target.parentNode.remove();
})
}
}
</script>
- 2 回答
- 0 关注
- 169 浏览
添加回答
举报