尝试使用 javascript 生成更多具有唯一名称的文件上传字段
我成功创建了一个添加文件上传字段的按钮、一个删除文件上传字段的按钮以及一个跟踪文件上传字段总数的计数器。问题是这些字段似乎没有唯一的名称。这些字段的名称应该是 img1、img2、img3 等...我可以看到它不起作用,因为文件没有上传到 SQL 表。
这是我的 JavaScript 和 HTML:
<script type="text/javascript">
var counter = 0;
function init(){
document.getElementById("counter").value=counter;
}
function add(){
counter++;
if (counter > 10){counter = 10;
}
else{
document.getElementById("counter").value=counter;
document.getElementById("addimg").innerHTML+="<input type='file' name='img'+counter>"+"<br>";}
}
function remove(){
counter--;
if (counter <= 0){counter = 0;}
document.getElementById("counter").value=counter;
document.getElementById("addimg").innerHTML="";
for (var i=1;i<=counter;i++)
{
document.getElementById("addimg").innerHTML+="<input type='file' name='img'+i>"+"<br>";
}
}
</script>
<body onLoad = "init()">
<button onClick="add()" >Add Photo</button>
<button onClick="remove()" >Remove a Photo</button><br>
<form method="POST" enctype='multipart/form-data'>
<div id="addimg">
</div>
<input type="text" id="counter" name="counter" value="">
<input type="submit" name="submit" value="submit">
</form>
</body>
I've managed to create a button that adds a file upload field, a button that removes a file upload field, and a counter that keeps track of the total number of file upload fields. The problem is that the fields don't seem to have unique names. The fields are supposed to have the names img1, img2, img3, etc... I can see its not working because the files weren't uploaded to the SQL table.
Here's my javascript and HTML:
<script type="text/javascript">
var counter = 0;
function init(){
document.getElementById("counter").value=counter;
}
function add(){
counter++;
if (counter > 10){counter = 10;
}
else{
document.getElementById("counter").value=counter;
document.getElementById("addimg").innerHTML+="<input type='file' name='img'+counter>"+"<br>";}
}
function remove(){
counter--;
if (counter <= 0){counter = 0;}
document.getElementById("counter").value=counter;
document.getElementById("addimg").innerHTML="";
for (var i=1;i<=counter;i++)
{
document.getElementById("addimg").innerHTML+="<input type='file' name='img'+i>"+"<br>";
}
}
</script>
<body onLoad = "init()">
<button onClick="add()" >Add Photo</button>
<button onClick="remove()" >Remove a Photo</button><br>
<form method="POST" enctype='multipart/form-data'>
<div id="addimg">
</div>
<input type="text" id="counter" name="counter" value="">
<input type="submit" name="submit" value="submit">
</form>
</body>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅此行:
counter will not be a part of the name
使用
此行中的相同错误:
See this line:
counter will not be a part of the name
Use
The same misstep in this line: