簡體   English   中英

使用Javascript動態生成文件上傳框

[英]Using Javascript to dynamically generate file upload boxes

我正在嘗試編寫一個 html/javascript 集(用 PHP 解釋),它允許用戶從 a 中 select 一個文件,然后一旦選擇該文件,它就會顯示另一個。

function displayFileInput() {
var counter = document.getElementById("counter").value;
var n = (parseInt(counter)+1).toString();
var element = document.getElementById("container");
var string = "<br /><input type = \"file\" name = \"file"+n+"\" onchange =\"javascript:displayFileInput()\"  />Default:<input type = \"radio\" name = \"main_picture\" value = \""+n+"\"  />";
element.innerHTML = element.innerHTML + string;
document.getElementById("counter").value=n;
return false;}

我使用的 HTML 代碼是這樣的:

<form enctype=\"multipart/form-data\" method = \"post\" action=\"newPost.php\" id = \"rental_form\">
<input type = \"text\" name = \"rent_name\" size = \"30\" value = \"Insert your post title here\"/><br />
<textarea rows= \"20\" cols = \"100\" name = \"rent_posttext\">
Insert your post text here!
</textarea><br />
<div id = \"container\">
<input type = \"file\" name = \"file1\" onchange = \"javascript:displayFileInput()\" />
Default:<input type = \"radio\" name = \"main_picture\" value = \"1\"  />
</div>
<input type = \"submit\" />
<input type = \"text\" id = \"counter\" value = \"1\" style = \"display:noe;\">

起初一切似乎都正常,但問題是:一旦我 select 一個文件,它正確顯示另一個文件框,但擺脫了前一個文件中的信息。 例如,在 Google Chrome 中,“選擇文件”輸入按鈕旁邊會顯示“未選擇文件”。

當我將表單提交到我的 PHP 腳本時,它會識別文件,但會為每個文件注冊一個“4”錯誤,這意味着沒有上傳任何文件。 不知何故,當它動態生成一個新的文件輸入時,它會擺脫所有的文件信息。 幫助!

您的問題是由以下部分引起的:

element.innerHTML = element.innerHTML + string;

這完全替換了您元素的內容,並在此過程中消除了任何先前的用戶選擇。 如果你使用appendChild而不是innerHTML =...;你會得到更好的結果 ,但這將需要重新處理您的代碼。

像這樣的東西應該工作:

function displayFileInput() {
    var counter = document.getElementById("counter").value;
    var n = (parseInt(counter)+1).toString();
    var element = document.getElementById("container");
    var newInput = document.createElement("div");
    var string = "<input type = \"file\" name = \"file"+n+"\" onchange =\"javascript:displayFileInput()\"  />Default:<input type = \"radio\" name = \"main_picture\" value = \""+n+"\"  />";
    newInput.innerHTML = string;
    element.appendChild(newInput);
    document.getElementById("counter").value=n;
    return false;
}

示例: http://jsfiddle.net/dsKFr/

此外,您不需要轉義 HTML 標記中的所有引號。 只是 JavaScript 版本(即使在那里,您也可以通過將單引號與雙引號交替來繞過它)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM