js实现上传文件添加和删除文件选择框实现上传文件添加和删除文件选择框
本文这里给大家说个用javascript实现的很实用的功能,是在上传附件的时候,可以动态地添加和删除文件选择框,然后一次
性上传。
从理论上看,实现起来比较容易,但实际工作的时候还是遇到两个难点,这些难点归结起来都是一个原因造成的,那就是浏览
器的兼容性。在脚本中要用到两个函数:insertAdjacentHTML和removeChild,而恰好这两个函数在Firefox下都不能正常使
用。几乎花费了一天的时候,在网上搜索着解决的方法,还好被找到了,也让我大松一口气。
具体两个函数是这样的:
<script type="text/javascript">
//删除文件选择框
function removeFile(id) {
var new_tr = id.parentNode;
try {
//new_tr.removeNode(true);
// just ie , not w3c;
// other idea
var tmp = new_tr.parentNode;
// 为了在ie和firefox下都能正常使用,就要用另一个方法代替,最取上一层的父结点,然后remove.
tmp.removeChild(new_tr);
} catch(e) {}
}
//添加文件选择框
function addFile(id)
{
var str = '<div><input type="file" runat="server" name="file" onKeyDown="this.blur();" oncontextmenu="return false" /><input
type="button" value="删除" style="height:22px;" onclick="removeFile(this)" /></div>'
insertHtml("beforeend",document.getElementById(id),str);
}
</script>
页面上这样引用:
<div>
<input type="button" value="添加附件(Add)" onclick="addFile('myfile')">
</div>
<div id="myfile">
</div>
在addFile函数中引用了另一个函数:insertHtml,这个函数主要是针对insertAdjacentHTML在firefox下无效的情况重写的,具
体可以通过搜索insertAdjacentHTML找到。
PS::清除file框的内容
<input type=file name=ttt>
<input type=button onclick="ttt.select();document.execCommand('Delete');" value=清除file框的内容>
第二个案例
文件上传,删除效果图:
刚开始:
点击按钮“选择更多后”,可以添加很多选择文件: