<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>无标题文档</title> <style> li{list-style:none;} li{position:relative;width:500px;} a{position:absolute;right:10px;} </style> <script> var count = 0; window.onload = function(){ var arrInput = document.getElementsByTagName(‘input‘); arrInput[0].focus(); arrInput[1].onclick = createMessageBoard; arrInput[2].onclick = batchDelete; }; function createMessageBoard(){ var arrInput = document.getElementsByTagName(‘input‘); var arrUl = document.getElementsByTagName(‘ul‘); if(arrInput[0].value == ‘‘){ alert(‘没有内容输入!‘); return false; } count++; if(arrUl[0].children.length >4){ var oLast = arrUl[0].lastElementChild || arrUl[0].lastChild; arrUl[0].removeChild(oLast); } var liNode = document.createElement(‘li‘); var checkNode = document.createElement(‘input‘); checkNode.type = ‘checkbox‘; checkNode.name = ‘delete‘; checkNode.innerHTML = arrInput[0].value; addElementNode(liNode,checkNode); liNode.appendChild(document.createTextNode(" "+count+"."+" "+arrInput[0].value)); /*添加文字节点*/ var aNode = document.createElement(‘a‘); aNode.href = ‘javascript:;‘; aNode.innerHTML = "删除"; aNode.onclick = function(){ arrUl[0].removeChild(this.parentNode); } liNode.appendChild(aNode); addElementNode(arrUl[0],liNode); arrInput[0].value = ""; } function addElementNode(obj,element){ if(obj.children[0]){ obj.insertBefore(element,obj.children[0]); /*在IE下如果第二个参数的节点不存在回报错,而在标准浏览器下不会出错,标准浏览器判断第二个参数不存在,则会自动转成appendChild添加*/ }else{ obj.appendChild(element); } } function batchDelete(){ var arrUl = document.getElementsByTagName(‘ul‘); var arrDeleteName = document.getElementsByName(‘delete‘); if(!arrDeleteName.length){ alert(‘未选中任何留言!‘); return false; } for(var i=0;i<arrDeleteName.length;i++){ if(arrDeleteName[i].checked){ arrUl[0].removeChild(arrDeleteName[i].parentNode); i--; //这里注意要减一个 } } } </script> </head> <body> <input type="text"/> <input type="button" value="增加留言"> <input type="button" value="批量删除"> <ul> </ul> </body> </html>
原文地址:https://www.cnblogs.com/moon-yyl/p/8954961.html
时间: 2024-10-07 16:45:22