1. 程式人生 > >JS實現動態增加和刪除li標籤行

JS實現動態增加和刪除li標籤行

function addDepartment()
{
var x = document.getElementById('department');
var l = x.childNodes.length;
var li = document.createElement("li");
li.className = "list_nr_bg";
li.innerHTML = "<span class='nr6'><select name='institute'><c:if test='${baseInstitutes !=null}'><c:forEach items='${baseInstitutes}' var='baseInstitute'><option value='${baseInstitute.id}'>${baseInstitute.instituteName}</option></c:forEach></c:if></select></span><span class='nr6'>專業:</span><span class='nr6'><input name='specialty' type='text'></span><span><input type='button' onclick='deleteDepartment(this)' value='刪除'></span>";
x.appendChild(li);
}

function deleteDepartment(obj)
{
if(window.confirm("確認刪除嗎?")){
var li = obj.parentNode.parentNode; //獲得當前行
var ul = li.parentNode;//獲得上一級標籤
ul.removeChild(li); //刪除當前行
} else {
return false;
}
}


HTML為:

<ul id="department">
<li class="list_nr_bg">
<span class="nr6">所屬院系:</span>
<span><input type="button" onclick="addDepartment()" value="增加"></span>
</li>
<li class="list_nr_bg">
<span class="nr6">
<select name="institute">
<c:if test="${baseInstitutes !=null}">
<c:forEach items="${baseInstitutes}" var="baseInstitute">
<option value="${baseInstitute.id}">${baseInstitute.instituteName}</option>
</c:forEach>
</c:if>
/select>
</span>
<span class="nr6">專業:</span>
<span class="nr6"><input name="specialty" type="text"></span>
</li></ul>