答案 0 :(得分:0)
您正在使用deleteSelect()
方法克隆节点,而您需要定位要删除的现有节点。
//Create a valid id
var name = select.getAttribute("name") + --selectionCounter;
//Target the element
var clone = document.getElementById(name);
//Remove the element
clone.parentNode.removeChild(clone);
此外,按下type="button"
var selectionCounter = 0;
function cloneSelect() {
var select = document.getElementById("List");
var clone = select.cloneNode(true);
var name = select.getAttribute("name") + selectionCounter++;
clone.id = name;
console.log(name)
clone.setAttribute("name", name);
document.getElementById("selectContainer").appendChild(clone)
}
function deleteSelect() {
var select = document.getElementById("List");
//Create a valid id
var name = select.getAttribute("name") + --selectionCounter;
//Target the element
var clone = document.getElementById(name)
clone.parentNode.removeChild(clone)
}
<div id="selectContainer">
<select id="List" name="List" required>
<option>Populated by php<option>
</select>
</div>
<button onclick="cloneSelect()" type="button" class="button">Add Room</button>
<button onclick="deleteSelect()" type="button" class="button" >Delete Room</button>
答案 1 :(得分:0)
var selectionCounter = 0;
function cloneSelect() {
var select = document.getElementById("List");
var clone = select.cloneNode(true);
var name = select.getAttribute("name") + selectionCounter++;
clone.id = name;
clone.setAttribute("name", name);
document.getElementById("selectContainer").appendChild(clone)
}
function deleteSelect() {
selectionCounter--;
var sel = document.getElementById("List"+(selectionCounter));
if (sel) document.getElementById("selectContainer").removeChild(sel);
}
<div id="selectContainer">
<select id="List" name="List" required>
<option>Populated by php<option>
</select>
</div>
<button onclick="cloneSelect()" type="button" class="button">Add Room</button>
<button onclick="deleteSelect()" type="button" class="button" >Delete Room</button>
答案 2 :(得分:0)
您可以使用<select>
(其中container.lastElementChild
引用您的container
元素)获取对最近添加的<div id="selectContainer">
的引用:
var counter = 0
var container = document.getElementById("selectContainer")
var select = document.getElementById("List")
function cloneSelect() {
var clone = select.cloneNode(true)
clone.id = clone.name = (select.name + counter++)
container.appendChild(clone)
}
function deleteSelect() {
if (counter) {
counter--
container.removeChild(container.lastElementChild)
}
}
&#13;
<div id="selectContainer">
<select id="List" name="List" required>
<option>Populated by php<option>
</select>
</div>
<button onclick="cloneSelect()" type="submit" class="button">Add Room</button>
<button onclick="deleteSelect()" type="submit" class="button">Delete Room</button>
&#13;