我有一個文件類型輸入按鈕,如果用戶選擇並且唯一安全的解決方案是完全銷燬輸入並重建它,則需要清除該文件類型輸入按鈕。我現在擁有的作品,但它是一個「豎琴槍」的解決方案,它只能工作一次。將onClick添加到JavaScript構建的輸入中
基本上,用戶有像這樣一個文件輸入:
<input type="file" name="filesToUpload" id="filesToUpload" onChange="makeFileList();" />
<ul id="fileList"><li>No Files Selected</li></ul>
而當他們選擇一個文件,他們可能需要清除徹底。
所以我這個正在經由其附加到文件列表中建立起來的:
function makeFileList() {
var input = document.getElementById("filesToUpload");
var ul = document.getElementById("fileList");
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
for (var i = 0; i < input.files.length; i++) {
var li = document.createElement("li");
var fileSize = input.files[i].size;
li.innerHTML = input.files[i].name +" "+ "<span id=\"lblSize\"></span><input onclick=\"clearFileInput()\" type=\"button\" value=\"Clear\" \/>";
ul.appendChild(li);
}
if(!ul.hasChildNodes()) {
var li = document.createElement("li");
li.innerHTML = 'No Files Selected';
ul.appendChild(li);
}
};
而且徹底摧毀該文件,功能重建的輸入,像這樣:
function clearFileInput(){
var oldInput = document.getElementById("filesToUpload");
var newInput = document.createElement("input");
newInput.type = "file";
newInput.id = oldInput.id;
newInput.name = oldInput.name;
newInput.className = oldInput.className;
newInput.style.cssText = oldInput.style.cssText;
// copy any other relevant attributes
oldInput.parentNode.replaceChild(newInput, oldInput);
};
所以我可以創建元素,添加文件類型,並使用舊的輸入ID,類和名稱。但我需要它具有相同的onChange =「makeFileList();。行爲以及
這裏是一個FIDDLE任何幫助表示讚賞
看看這裏:http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery – STT 2014-10-09 13:18:54