JavaScript编写简单的增加与减少元素
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9 </head> 10 11 <body> 12 <ul> 13 <li class="diyi"> 14 <a href="">第1个li</a> 15 </li> 16 <li> 17 <a href="">第2个li</a> 18 </li> 19 <li> 20 <a href="">第3个li</a> 21 </li> 22 <li> 23 24 25 <a href="">第4个li</a> 26 </li> 27 </ul> 28 <input type="button" value="点击增加第一个"> 29 <input id="dier" type="button" value="点击减少第一个"> 30 <input id="disan" type="button" value="点击增加最后一个"> 31 <input id="disi" type="button" value="点击减少最后一个"> 32 <script> 33 let i = 0; 34 let j = 0; 35 let ul = document.querySelector('ul');//找到ul 36 let input = document.querySelector('input');//找到第一个input 37 input.onclick = function () { 38 let first = ul.firstElementChild;//将元素第一个子节点存入first中 39 let n = document.createElement('li');//创建元素li 40 ul.insertBefore(n, first);//将创建的元素li放入ul中 41 i++; 42 n.innerHTML = `<a href="#">增加第${i}个li</a>`; 43 } 44 let dier = document.querySelector('#dier');//找到第二个input 45 dier.onclick = function () { 46 let first = ul.firstElementChild; 47 let n = document.createElement('li'); 48 ul.removeChild(first);//删除节点 49 i--; 50 n.innerHTML = `<a href="#">减少第${i}个li</a>`; 51 } 52 let disan = document.querySelector('#disan');//找到第三个input 53 disan.onclick = function () { 54 let n1 = document.createElement('li'); 55 ul.appendChild(n1); 56 j++; 57 n1.innerHTML = `<a href="#">增加最后第${j}个li</a>`; 58 } 59 let disi = document.querySelector('#disi');//找到第四个input 60 disi.onclick = function () { 61 let last = ul.lastElementChild; 62 let n = document.createElement('li'); 63 ul.removeChild(last);//删除节点 64 j--; 65 n.innerHTML = `<a href="#">增加第${i}个li</a>`; 66 } 67 </script> 68 </body> 69 70 </html>