[英]innerHTML error in syntax not working; Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
[英]Error: Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
我試圖創建一個待辦事項列表,在一個輸入標簽的幫助下,我想通過動態添加 HTML 來輸入所有待辦事項列表,但是在刪除時,我想從相反的順序中刪除它,然后以不同的方式實現它; 如果我按下刪除按鈕,我會在控制台部分收到錯誤,如下圖所示: ; 任何人都可以在我的代碼中找到問題,如果我只測試單獨刪除 function 那么它可以工作,但不能在下面提到的代碼中
<body>
<div>Hello world</div>
<div id="li">
<input type="text" id="liin" name="in"/>
<button name="add" onclick=add() className="btn btn-light">add</button>
</div>
<script>
var i =1;
function add() {
let temp = document.getElementById('liin').value;
document.getElementById('li').innerHTML+=`<br><span id="divli${i}">${temp}</span>
<button name="add" onclick=remove() className="btn btn-light">remove</button>`;
i++;
}
function remove() {
document.getElementById(`divli${i}`).innerHTML ='';
i--;strong text
}
</script>
</body>
嘗試這個。 您在代碼中增加 i 值為時已晚,因此您對 select 的引用該元素來自 null。 您要做的另一件事是將 class 添加到要在刪除 function 中選擇和刪除的每個“刪除”按鈕中。 這也可以動態完成。
<body> <div>Hello world</div> <div id="li"> <input type="text" id="liin" name="in"/> <button name="add" onclick=add() className="btn btn-light">add</button> </div> <script> var i = 0; function add() { i++; let temp = document.getElementById('liin').value; document.getElementById('li').innerHTML+=`<br><span id="divli${i}">${temp}</span> <button name="add" onclick=remove() id="divli${i}" className="btn btn-light">remove</button>`; } function remove() { // document.getElementById(`divli${i}`).innerHTML = ''; let nodeList = document.querySelectorAll(`#divli${i}`); nodeList.forEach(node => node.remove()); i--; } </script> </body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.