本文有大部分为转载,经过添加部分功能。感谢创作者提供的便利。如有问题请联系我,及时处理此文。
<!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=utf-8" />
<title>js 动态增加file实现多文件上传功能</title>
</head>
<body>
<script language="javascript">
//全局变量,代表文件域的个数,并用该变量区分文件域的name属性
var file_count = 0;
//增加文件 域
function additem(id) {
if (file_count > 9) {
alert("最多9个");
return;
}
//定义行变量row;单元格变量cell;单元格内容变量str。
var row,cell;
var str='';
//在指定id的table中插入一行
row = eval("document.all['"+id+"']").insertRow();
if(row != null ) {
//设置行的背景颜色
row.bgColor="white";
//在行中插入单元格
cell = row.insertCell();
//设置str的值,包括一个文件域和一个删除按钮
str='<input onselectstart="return false" class="tf" οnpaste="return false" type="file" name="file[' + file_count + ']" style="width:500px" οnkeydοwn="return false;"/>';
str += ' <input type="button" value="删除" οnclick="deleteitem(this,\'tb\');">';
//文件域个数增加
file_count++;
//设置单元格的innerHTML为str的内容
cell.innerHTML=str;
}
}
//删除文件域
function deleteitem(obj,id) {
var rowNum,curRow;
curRow = obj.parentNode.parentNode;
rowNum = eval("document.all."+id).rows.length - 1;
eval("document.all['"+id+"']").deleteRow(curRow.rowIndex);
file_count--;
}
//显示上传的文件名
function show(){
var tf=document.getElementsByClassName('tf');
//var pname=tf.value;
var str='';
for(var i=0;i<tf.length;i++){
var s=tf[i].value;
str=str+s+';';
}
document.getElementById('picshow').innerHTML=str;
}
</script>
<table cellspacing="0" id="tb" style="width:400px">
</table>
<input type=button value="显示" οnclick='show()'/>
<div id="picshow"></div>
</body>
</html>