我是 JS 新手,需要你的帮助!
\n我有一个上传公式,用户可以将多个文件添加到数据库(php、mysql)。
\n现在我希望输入按钮将动态添加,意味着当填充 1 个字段时,会显示另一个字段,依此类推。
\n每个文件都有一个标题字段,它看起来像这样
Add one more file\n+--------------+ +---------------+\n| | | + |\n| \xe3\x83\xbd( \xe2\x89\xa7\xcf\x89\xe2\x89\xa6)\xe3\x83\x8e | | ++++++ |\n| | | + |\n+--------------+ +---------------+\n> Titel ABC < > ______________<\nRun Code Online (Sandbox Code Playgroud)\n\n我会隐藏输入按钮,并将其替换为带有“+”或其他内容的图像,但这不是这个问题的一部分,只是你可以看到,我在一天结束时试图达到的目标:)
\n\n这是我在互联网上找到的代码并进行了一些编辑,但是我在用input=file + input=text替换“选项”时遇到问题。因此,当用户单击“添加”时,将显示一个选择按钮和一个文本字段。
\n\n Add one more file\n+--------------+ +---------------+\n| | | + |\n| \xe3\x83\xbd( \xe2\x89\xa7\xcf\x89\xe2\x89\xa6)\xe3\x83\x8e | | ++++++ |\n| | | + |\n+--------------+ +---------------+\n> Titel ABC < > ______________<\nRun Code Online (Sandbox Code Playgroud)\r\nfunction add(type) {\r\n //Create an input type dynamically.\r\n var element = document.createElement("input");\r\n\r\n //Assign different attributes to the element.\r\n element.setAttribute("type", type);\r\n element.setAttribute("value", type);\r\n element.setAttribute("name", type);\r\n\r\n var foo = document.getElementById("fooBar");\r\n\r\n //Append the element in page (in span).\r\n foo.appendChild(element);\r\n}Run Code Online (Sandbox Code Playgroud)\r\n* {\r\n margin: 0;\r\n padding: 0;\r\n font-family: Arial;\r\n}\r\n\r\nbody {\r\n background-color: grey;\r\n}\r\n\r\nh1 {\r\n color: white;\r\n}\r\n\r\nh2 {\r\n color: darkgrey;\r\n}Run Code Online (Sandbox Code Playgroud)\r\n您想要创建一个 div 并使用appendChild添加文件和输入字段:
window.addEventListener("load", function() {
document.getElementById("add").addEventListener("click", function() {
// Create a div
var div = document.createElement("div");
// Create a file input
var file = document.createElement("input");
file.setAttribute("type", "file");
file.setAttribute("name", "file"); // You may want to change this
// Create a text input
var text = document.createElement("input");
text.setAttribute("type", "text");
text.setAttribute("name", "text"); // you may want to change this
// add the file and text to the div
div.appendChild(file);
div.appendChild(text);
//Append the div to the container div
document.getElementById("container").appendChild(div);
});
});Run Code Online (Sandbox Code Playgroud)
* {
margin: 0;
padding: 0;
font-family: Arial;
}
body {
background-color: grey;
}
h1 {
color: white;
}
h2 {
color: darkgrey;
}Run Code Online (Sandbox Code Playgroud)
<h1>Add input elements dynamically</h1>
<form>
<div>
<input type="button" value="add" id="add" />
<div id="container"> </div>
</div>
</form>Run Code Online (Sandbox Code Playgroud)