javascript之動態新增和刪除按鈕節點
阿新 • • 發佈:2019-01-26
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> .file-item{ width: 300px; height: 30px; margin:5px 0; box-shadow: 0 0 10px rgba(0,0,0,0.3); } </style> </head> <body> <h1>檔案上傳</h1> <input type="file" name="file" /><button id='btn'>add more...</button> <div id="file-box"> </div> <script> $('btn').addEventListener('click',function(){ //建立DIV var fileItem = document.createElement('div'); fileItem.className = 'file-item'; //建立input元素,type為file,name為file var input = document.createElement('input'); input.type = input.name = 'file'; fileItem.appendChild(input); //建立按鈕 var btn = document.createElement('button'); btn.textContent = '刪除'; fileItem.appendChild(btn); $('file-box').appendChild(fileItem); //為按鈕設定點選事件(刪除) btn.addEventListener('click',function(){ //刪除當前按鈕節點所在父節點 // $('file-box').removeChild(this.parentNode); this.parentNode.remove(); }) }); function $(id){ return document.getElementById(id); } </script> </body> </html>