<!DOCTYPE html> <html> <head> <meta charset="gb2312"> <title></title> </head> <body> <div id="testDiv" onclick="delFile(event)" > <input id="stopbubble" type="button" value="增加" onclick="addFile(event)" /> </div> <script type="text/javascript"> function addFile(event) { var div = document.getElementById("testDiv"); div.insertAdjacentHTML("beforeEnd", "<input type=‘file‘ onclick=‘stopProp(event)‘/> <input type=‘button‘ value=‘删除‘ /><br>"); event.stopPropagation(); //阻止添加新标签时冒泡 } function stopProp(event) { event.stopPropagation();//阻止上传文件时冒泡 } function delFile(event) { var par = document.getElementById("testDiv"); var listItems = par.getElementsByTagName("input"); if (event.target.tagName.toLowerCase() === ‘input‘) { var aindex = [].indexOf.call(listItems, event.target);//获取当前删除的节点索引 par.removeChild(listItems[aindex - 1]);//删除前一个 } par.removeChild(event.target);//删除后一个 } </script> </body> </html>
在页面可以动态的添加及删除上传文件标签,实现效果如下
原文:https://www.cnblogs.com/liyunworld/p/11168917.html