我有一个上传文件的表单..
<form enctype="multipart/form-data" name="" action="" method="POST">
<input type="file" name="file[]" id="files" multiple />
<div id="selectedFiles"></div>
<form>
用于显示名称和大小的javascript函数。
<script>
var selDiv = "";
document.addEventListener("DOMContentLoaded", init, false);
function init() {
document.querySelector('#files').addEventListener('change', handleFileSelect, false);
selDiv = document.querySelector("#selectedFiles");
}
function handleFileSelect(e) {
if(!e.target.files) return;
selDiv.innerHTML = "";
var files = e.target.files;
for(var i=0; i<files.length; i++) {
var f = files[i];
selDiv.innerHTML += "<span class='attach'>" + f.name + " <" + f.size + " bytes>" + "</span>";
}
}
</script>
他们是否知道如何在附件上制作删除功能?
示例:
图像显示上传的文件..和红色&#34; x&#34;是删除... 有人可以帮我这个吗?使用javascript ..
答案 0 :(得分:1)
见下面的评论。
<form action="some.php" method="post" id="form">
<input type="file" id="file" multiple style="display: none;" />
<button type="button" id="button">Select files</button>
<div id="selectedFiles"></div>
<button type="submit" id="submit">Upload</button>
<form>
var selDiv = document.querySelector("#selectedFiles");
document.querySelector("#button").addEventListener("click", function() {
document.querySelector("#file").click();
}, false);
document.querySelector("#file").addEventListener("change", function() {
var files = this.files;
for (var i = 0; i < files.length; ++i) {
var file = files[i],
span = document.createElement("span");
span.className = "attach";
span.innerHTML = file.name+" <"+file.size+" bytes>";
span.file = file;
var remove = document.createElement("span");
remove.innerHTML = "Remove";
span.appendChild(remove);
selDiv.appendChild(span);
remove.addEventListener("click", function() {
this.parentNode.removeChild(this);
}, false);
}
}, false);
document.querySelector("#form").addEventListener("submit", function(e) {
var files = selDiv.querySelectorAll("span.attach"),
data = new FormData(),
xmlhttp = new XMLHttpRequest();
for (var i = 0; i < files.length; ++i) {
data.append("file[]", files[i].file);
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
selDiv.innerHTML = "Uploading completed!";
}
}
xmlhttp.open("POST", "upload.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
return false;
}, false);