您的位置:首页 > Web前端 > JavaScript

js实现多文件上传

2016-07-08 18:30 399 查看
js实现多文件上传

HTML代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="util.js"></script>
<script>
//多文件上传 例子 练习dom操作 和动态事件绑定
function addFile(){
//获取新添加的文件的input 的标签的容器
var con=$("#container");
//创建我们的file文件域
var fileInp=document.createElement("input");
//设置input 的类型为file
fileInp.type="file";
//创建我们的删除按钮
var butInp=document.createElement("input");
//设置类型和 按钮的名字
butInp.type="button";
butInp.value="删除";
//创建一个换行
var br=document.createElement("br");
//从前面正向添加
con.insertBefore(br,con.firstChild);
con.insertBefore(butInp,con.firstChild);
con.insertBefore(fileInp,con.firstChild);
//注释的部分为尾部添加 前面的代码注释起来 执行下面即可
// con.appendChild(fileInp);
// con.appendChild(butInp);
// con.appendChild(br);
butInp.onclick=function(){
con.removeChild(br);
con.removeChild(butInp);
con.removeChild(fileInp);
}
}

</script>
</head>
<body>
<form action="test.html" method="get">
<input type="file" />
<input type="button" value="添加" onclick="addFile()" />
<div id="container" >

</div>
</form>
</body>
</html>

js代码:

/**
*
* @param idOrName 如果传入id 前面加上# 如果传入name 直接传入
* @returns {*} 返回元素节点 如果没找到 返回null
*/
function $(idOrName){
var obj=null;
if(idOrName){
if(idOrName.charAt(0)=="#"){
obj=document.getElementById(idOrName.substring(1));
}else{
obj=document.getElementsByName(idOrName);
}
}
return obj;
}
/**
*
* @param parentNode 父节点
* @returns {Array} 所有的元素子节点
*/
function getChildNodes(parentNode){
var childs=parentNode.childNodes;
var newChilds=[];
for(var i=0;i<childs.length;i++){
if(childs[i].nodeType==1){
newChilds.push(childs[i]);
}
}
return newChilds;
}
/**
*
* @param parentNode 父节点
* @returns {*|Node} 第一个元素节点
*/
function getFirstChild(parentNode){
var firstChild=parentNode.firstChild;
if(firstChild.nodeType==3){
firstChild=firstChild.nextSibling;
}
return firstChild;

}
/**
*
* @param parentNode 父节点
* @returns {*|Node} 最后一个元素节点
*/
function getLastChild(parentNode){
var lastChild=parentNode.lastChild;
if(lastChild.nodeType==3){
lastChild=lastChild.previousSibling;
}
return lastChild;
}
/**
*
* @param node 元素节点
* @returns {*|Node} 返回下一个兄弟元素节点
*/
function getNextSibling(node){
var nextNode=node.nextSibling;
if(nextNode.nodeType==3){
nextNode=nextNode.nextSibling;
}
return nextNode;
}
/**
*
* @param node 元素节点
* @returns {*|Node} 返回前一个兄弟元素节点
*/
function getPreviousSibling(node){
var preNode=node.previousSibling;
if(preNode.nodeType==3){
preNode=preNode.previousSibling;
}
return preNode;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: