首页 > 解决方案 > 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>&nbsp;<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?

标签: javascriptjqueryarraysimage

解决方案


您的代码与数组无关。

相反,您正在尝试从 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(),因此您可能需要重新调整那部分代码。


推荐阅读