如下所示:
function addDepartment()
{
<span style="white-space:pre"> </span>var x = document.getElementById('department');
<span style="white-space:pre"> </span>var l = x.childNodes.length;
<span style="white-space:pre"> </span>var li = document.createElement("li");
<span style="white-space:pre"> </span>li.className = "list_nr_bg";
<span style="white-space:pre"> </span>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>";
<span style="white-space:pre"> </span>x.appendChild(li);
}
function deleteDepartment(obj)
{
<span style="white-space:pre"> </span>if(window.confirm("確認刪除嗎?")){
<span style="white-space:pre"> </span>var li = obj.parentNode.parentNode; //獲得當前行
<span style="white-space:pre"> </span>var ul = li.parentNode;//獲得上一級標簽
<span style="white-space:pre"> </span>ul.removeChild(li); //刪除當前行
<span style="white-space:pre"> </span>} else {
<span style="white-space:pre"> </span>return false;
<span style="white-space:pre"> </span>}
}
HTML:
<ul id="department">
<span style="white-space:pre"> </span><li class="list_nr_bg">
<span style="white-space:pre"> </span><span class="nr6">所屬院系:</span>
<span style="white-space:pre"> </span><span><input type="button" onclick="addDepartment()" value="增加"></span>
<span style="white-space:pre"> </span></li>
<span style="white-space:pre"> </span><li class="list_nr_bg">
<span style="white-space:pre"> </span><span class="nr6">
<span style="white-space:pre"> </span><select name="institute">
<span style="white-space:pre"> </span><c:if test="${baseInstitutes !=null}">
<span style="white-space:pre"> </span><c:forEach items="${baseInstitutes}" var="baseInstitute">
<span style="white-space:pre"> </span><option value="${baseInstitute.id}">${baseInstitute.instituteName}</option>
<span style="white-space:pre"> </span></c:forEach>
<span style="white-space:pre"> </span></c:if>
<span style="white-space:pre"> </span>/select>
<span style="white-space:pre"> </span></span>
<span style="white-space:pre"> </span><span class="nr6">專業:</span>
<span style="white-space:pre"> </span><span class="nr6"><input name="specialty" type="text"></span>
<span style="white-space:pre"> </span></li></ul>
以上就是小編為大家帶來的JS實現動態增加和刪除li標簽行的實例代碼全部內容了,希望大家多多支持~