我正在嘗試用 javascript 制作一個板。li在這樣做時,我在添加新內容時遇到了麻煩ul。會有多個ul,用戶可以li通過ul單擊“add_card”按鈕添加。我確實嘗試過,但它僅添加到第一個ul.這是我嘗試過的。超文本標記語言<main><div id="myTitle" class="bigTitle"> <input type="text" id="myInput" placeholder="TItle..."> <span onclick="newElement()" class="addBtn">Add</span></div><div id="myBoard"> <div id="myUL-con"> <h3 contenteditable="true">Things to do</h3> <span class="close close_list"></span> <ul id="myUL" runat="server"> <li id="node" draggable="true" ondragstart="drag(event)"> <h4 id="sm_title" contenteditable="true">Do the meditation</h4> <span contenteditable="true">- before going to sleep</span> </li> </ul> <span id="add_card" onclick="addCard()" type="button"></span> </div> </div>CSS/* When clicked on, add a background color and strikeout text */ul li.checked { background: rgba(106, 140, 168, 0.82); color: #f4f5f7; text-decoration: line-through}/* Add a "checked" mark when clicked on */ul li.checked::before { content: ''; position: absolute; border: solid #f4f5f7; border-width: 0 2px 2px 0; top: 10px; left: 16px; transform: rotate(45deg); height: 15px; width: 7px}另外,請讓我知道我應該在哪里編寫代碼,以便使所有添加的li功能都具有與現有功能類似的功能,li因為應該起作用的功能也不起作用。
1 回答

臨摹微笑
TA貢獻1982條經驗 獲得超2個贊
您的代碼的行為方式是因為您將每個新的 li 元素附加到代表第一張卡的“myUL”。
你應該做的是給每個新元素一個唯一的 id。
我這樣做的方式是在添加新元素時:
? ? ? let ulIdx = 1;
? ? ? ulIdx++;
? ? ? let myUL_id = "myUL"+ulIdx.toString();
? ? ? myUl.setAttribute("id", myUL_id);
newUl.appendChild(add_card);
add_card.id = "add_card"+ulIdx.toString();
add_card.innerText = "Add li element";
add_card.setAttribute("onclick", "addCard(this)");
然后在函數 addCard(el){} 中,包含以下行;
? var add_LI_element = el.getAttribute("id");
? var elIndex = add_LI_element.charAt(add_LI_element.length -1);
? var ul = document.getElementById("myUL"+elIndex);
- 1 回答
- 0 關注
- 118 瀏覽
添加回答
舉報
0/150
提交
取消