Problem to remove an img tag inside the array by the id of the image

0

I'm previewing images with image removal. In case I need to remove the selected element from within the array using the id of the img tag. I can already take the id to the function it will remove, however, I can not access the image element by its id inside the array.

Here is the code for review:

for (var i = 0, f; f = files[i]; i++) {

        // Only process image files.
          if (!f.type.match('image.*')) {
            continue;
          }

        var reader = new FileReader();

        reader.onload = function (e) {
            base64imgs.push("<img class='thumb' id='img_"+id+"' src='"+e.target.result+"' >");
        };

        reader.readAsDataURL(f);
    } 

$('#output_box_foto').append("<img class='thumb' id='img_"+id+"' src='"+URL.createObjectURL(files_show[i])+"' onclick='Remover("+id+")'>");

function Remover(id) {
    id_img_remove="#img_"+id;
    $(id_img_remove).remove(); 
    //Acima eu apenas removo visualmente a imagem, e abaixo seria o trecho de código que não sei como fazer para remover o elemento de dentro do meu array. Aqui no caso eu gostaria de remover o elemento IMG pelo Id dele de dentro do array
    base64imgs // Já tentei slice, preg...sem êxito
} 
    
asked by anonymous 09.03.2017 / 01:34

1 answer

1

Friend,

The base64 array contains strings and not objects, so I believe you need to search for text instead of a selector.

It would look something like this:

var meuarray = [
        '<img id="img1" src="img1.jpg" />',
        '<img id="img2" src="img2.jpg" />',
        '<img id="img3" src="img3.jpg" />'
    ];

    var index = -1;

    $(meuarray).each(function (i, item) {

        if (item.indexOf('id="img1"') > -1)
        {
            index = i;
        }
    });

    if (index > -1) {
        meuarray.splice(index, 1);
    }

    console.log(meuarray);

Additionally ...

If you want to work with jQuery selectors, I suggest you create your objects with jQuery rather than append with text. For example this block:

  

$('#output_box_foto').append("<img class='thumb' id='img_"+id+"'src='"+URL.createObjectURL(files_show[i])+"' onclick='Remover("+id+")'>");

It would look like this:

var imgBoxFoto = $('<img>', {
    class: "thumb", 
    id: "meuid", 
    src:"minhaurl"
}).on("click", function(el){
    Remover(id);
});

$('#output_box_foto').append(imgBoxFoto);

Note that you can also override the onclick attribute of the html and register directly into the object, without your "id" and method name being exposed in html.

Turning your text array (from img tags) into objects would look like this:

    //array de objetos jQuery
    var meuarray2 = [
        $('<img>', { id: 'img1', src: 'img1.jpg' }),
        $('<img>', { id: 'img2', src: 'img2.jpg' }),
        $('<img>', { id: 'img3', src: 'img3.jpg' })
    ];

    //Os objetos criados em memória no jQuery ficam com formato de function "n.fn.init[1]"
    //Precisa transformá-los em objetos referenciáveis com o array:
    meuarray2 = $(meuarray2).map(function () { return this.toArray(); });

    //usa o filter passando o id -- Também poderia ser qualquer seletor (classe, data, type, etc)
    var index = meuarray2.index($(meuarray2).filter('#img1'));

    //faz o splice para eliminar o valor:
    if (index > -1) {
        meuarray2.splice(index, 1);
    }

    console.log(meuarray2);
    
09.03.2017 / 05:24