使用JS实现页面中动态添加文件上传输入项
1. 编写JSP
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4 <head> 5 <title>My JSP 'upload2.jsp' starting page</title> 6 <script type="text/javascript“ src="js/test.js"></script> 7 </head> 8 <body> 9 <table> 10 <tr> 11 <td>上传用户:</td> 12 <td><input type="text" name="username"></td> 13 </tr> 14 <tr> 15 <td>上传文件:</td> 16 <td><input type="button" value="添加上传文件" onclick="addinput()"></td> 17 </tr> 18 <tr> 19 <td></td> 20 <td> 21 <div id="file"> 22 23 </div> 24 </td> 25 </tr> 26 </table> 27 </body> 28 </html>
2. 编写JavaScript
test.js
1 function addinput(){ 2 var div = document.getElementById("file"); 3 4 var input = document.createElement("input"); 5 input.type="file"; 6 input.name="filename"; 7 8 var del = document.createElement("input"); 9 del.type="button"; 10 del.value="删除"; 11 del.onclick = function d(){ 12 this.parentNode.parentNode.removeChild(this.parentNode); 13 } 14 15 16 var innerdiv = document.createElement("div"); 17 18 19 innerdiv.appendChild(input); 20 innerdiv.appendChild(del); 21 22 div.appendChild(innerdiv); 23 }
3. 效果演示