1 回答

TA貢獻1796條經驗 獲得超4個贊
解決方案
HTML:
<div class="parent-row">
? <h1>Add a new Post</h1>
? <div>
? ? <input type="text" class="put" />
? ? <button class="add">Add a Post</button>
? ? <button class="remove">Remove a Post</button>
? </div>
? <ul class="menu">
? ? <li>Albenis</li>
? </ul>
</div>
腳本:
const add = document.querySelector(".add");
const remove = document.querySelector(".remove");
add.addEventListener("click", function () {
? const cont = document.querySelector(".menu");
? const input = document.querySelector(".put");
? const newli = document.createElement("LI");
? newli.innerText = input.value;
? cont.append(newli);
});
remove.addEventListener("click", function () {
? const df = document.querySelector(".menu");
? df.firstElementChild.remove();
});
你的錯誤
您的錯誤是您試圖newli
從其代碼塊外部獲取常量,請記住const
變量的范圍僅限于該塊。
一種不同的方法
這種方式更簡單一些,允許您刪除任何帖子,而不僅僅是最后添加的帖子。
const postBtn = document.querySelector('#post')
const list = document.querySelector('#list')
postBtn.addEventListener('click', () => {
? const text = document.querySelector('#post-text')
? list.innerHTML += `<li>${text.value} <button id="remove" onclick="remove(event)">remove</button></li>`
? text.value = ''
})
const remove = (e) => {
?e.target.parentElement.remove()
}
<div>
? <h1>Make a post</h1>
? <input id="post-text" type="text" placeholder="Text"><button id="post">Post</button>
? <ul id="list">
? </ul>
</div>
添加回答
舉報