[英]How to add a <form > tag dynamically to the li items of an ul that are also being created dynamically
一個JavaScript函數,可在其中使用<input>
動態重復ul
:
function createEditableLi(ulId) {
const ul = document.getElementById(ulId);
const newLi = document.createElement("li");
const newinput = document.createElement("input");
newinput.setAttribute("class", "input_style");
newinput.setAttribute("id", "textboxId");
newinput.setAttribute("type", "text");
newinput.setAttribute("name", "card_name");
newLi.setAttribute("id", "editableLi");
ul.appendChild(newLi);
newLi.appendChild(newinput);
}
它創建HTML為
<li id="editableLi">
<input name="card_name" type="text" id="textboxId" class="input_style" />
</li>
但我希望我的html可以像這樣用javascript
<form action="./card-controller-task-pending" method="POST">
<li id="editableLi">
<input name="card_name" type="text" id="textboxId" class="input_style" />
</li>
</form>
我開始回答,但是@ADyson對此評論很好-這將是通用方法:
function createEditableLi() { const container = document.getElementById('demo'); const newForm = document.createElement("form"); newForm.setAttribute("method", "post"); newForm.setAttribute("action", "URL"); // change this const newUl = document.createElement("ul"); const newLi = document.createElement("li"); newLi.setAttribute("id", "editableLi"); const newinput = document.createElement("input"); newinput.setAttribute("class", "input_style"); newinput.setAttribute("id", "textboxId"); newinput.setAttribute("type", "text"); newinput.setAttribute("name", "card_name"); newLi.appendChild(newinput); newUl.appendChild(newLi); newForm.appendChild(newUl); container.appendChild(newForm); } createEditableLi();
<div id="demo"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.