javascript - How to delete an image in array of images in javascript while maintaining current image list on browser screen?
问题描述
I have an array of images that I uploaded to the browsers screen as follows:
...
<input type="file" id="image" accept="image/*" name="image[]" multiple /><br/>
<div id="images"></div>
$('#image').change(function(){
for (i = 0; i < $(this)[0].files.length; i++) {
imageCount = imageCount + 1;
$("#images").append('<div style="width:100px;"><img src="'+window.URL.createObjectURL(this.files[i])+'" id="images" width="100px" height="100px"/>'+'<button type="button" onclick="uploadImage('+imageCount+');">Upload </button> <button type="button" onclick="removeImage('+imageCount +');">X</button></div> nbsp;');
}
});
function removeImage(position) {
images = $('#images');
alert("Position: "+position);
}
...
How would one go about removing an image at a specific position in the image array?
解决方案
您的代码与数组无关。
相反,您正在尝试从 DOM 中添加/删除元素。与其尝试动态分配值,不如onclick
使用事件处理程序。
还需要注意的是,使用您的代码,您最终会得到多个元素id="image"
,这是无效的。ID 必须是唯一的。 相反,使用类。另请参阅模板文字和.on()
<input type="file" id="add_images" accept="image/*" multiple />
<div id="images"></div>
$('#add_images').on('change', function(){
$.each(this.files, function(file) {
$('#images').append(`
<div style="width:100px;">
<img class="image" src="${window.URL.createObjectURL(file)}">
<button class="upload_image">Upload</button>
<button class="remove_image">X</button>
</div>`);
});
});
$('#images') //this replaces the onclick="" method
.on('click', 'button.remove_image', function() {
this.parentElement.remove();
});
.on('click', 'button.upload_image', function() {
//code for uploading image
});
不能说我曾经使用过URL.createObjectURL(),因此您可能需要重新调整那部分代码。
推荐阅读
- c++ - 在编译时拆分字符串会在不同的编译器上产生不同的结果
- python - NameError 未定义
- laravel - 在 Laravel phpunit 测试中获取请求搜索不同的 url
- elasticsearch - 考虑弹性搜索查询中的每个单词
- sqlite - 尝试更新单行中的多个字段,但创建重复行
- r - R - 从 [ 符号后的列名中删除文本
- javascript - Webpack4:两个基于入口点的供应商库
- javascript - 尝试在 javascript 中将图像转换为 Base64 字符串并尝试在 c# 中转换为字节数组,在 base64 字符串中出现 Invalid character 错误
- python - 在 Visual Studio Code 中使用 Pybluez 时出现“ImportError: No module named bluetooth”
- docusignapi - 修复 TLS 版本上的 DocuSign SOAP API 错误