gpt4 book ai didi

javascript - 保留选定的图像而不是用新图像替换

转载 作者:行者123 更新时间:2023-11-30 14:32:30 24 4
gpt4 key购买 nike

我正在尝试创建一个 HTML 文件输入字段,它可以多次添加文件(在本例中为图像),而不是替换现有的选定文件。

文件字段将始终替换之前的选择。我想做的是每次用户选择文件时将选择存储在其他地方。

$("#imageInput").change(function() {
if(typeof window.images == "undefined"){
window.images = this.files;
}
else {
var k = 0;
console.log(window.images.length); //always equals to this.files.length
for (var i = window.images.length; i < window.images.length + this.files.length; i++) {
window.images[i] = this.files[k];
k++;
}
}
});

HTML 输入标签:

<input type="file" id="imageInput" multiple accept="image/*">

这个解决方案不起作用,因为 window.images 数组总是在选择新文件时重置。

最佳答案

索引:

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

  
var images = [];
var imagesName = [];
$("#imageInput").change(function() {

for(var i=0;i<this.files.length;i++)
{

if(imagesName.indexOf(this.files[i].name)==-1)
{
console.log(this.files[i]);
images.push(this.files[i]);
imagesName.push(this.files[i].name);
}

}

console.log(imagesName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="file" id="imageInput" multiple accept="image/*">

关于javascript - 保留选定的图像而不是用新图像替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com