Exchange images with Jquery

Asked

Viewed 194 times

1

Guys, I’m trying to change an image at the click of the button and I’m not getting it, jquery returns me this error:
inserir a descrição da imagem aqui

I’m trying to make the exchange using the date attribute.
My Jquery code:

$('#botao_troca_imagem').on('click',function() {
        jQuery().data('imagem').attr("src", "/public/default/images/marker.png");
        $("#botao_troca_imagem").remove();
});

My HTML code:

<figure>

  <img data-imagem="troca_imagem" src="/public/default/images/mapa-google.jpg">

  <figcaption>

  <button id="botao_troca_imagem" role="button">Mostrar mapa</button>

  </figcaption>
</figure>

4 answers

2


This error happens because the element you are selecting to exchange does not have the "src" property or better, you are not actually selecting an element, in case you have to select the img tag you want to exchange:

$('#botao_troca_imagem').on('click',function() {
    $('img[data-imagem="troca_imagem"]').attr("src", "/public/default/images/marker.png");
    $("#botao_troca_imagem").remove();
});

1

You can change as follows:

$('#botao_troca_imagem').on('click',function() {
 document.querySelector('.classe_imagem').src='/public/default/images/marker.png';
});

1

When using date you should use the Jquery selector differently, something like: $("[data-slide='meu-slides']");, see the example in Jsfiddle In your case it would look like this:

$('#botao_troca_imagem').on('click',function() {
        $('img[data-imagem="troca_imagem"]').attr("src", "https://www.irdes.fr/imgs2017/images/about-imgs.jpg");
        $("#botao_troca_imagem").remove();
});

0

You want to select the element by attribute data-imagem that contains the value troca_imagem.

The method .data() returns a value and not an element, such as the .val(). To select an element by the value of an attribute, you use brackets [] with the attribute and value:

$("[atributo='valor']")

In your case I’d be:

$('[data-imagem="troca_imagem"]')

You don’t necessarily have to tag img before the brackets, assuming that this attribute and value only exists in img.

Your code would look better this way:

$('#botao_troca_imagem').on('click',function() {
   $('[data-imagem="troca_imagem"]').attr("src", "/public/default/images/marker.png");
   $(this).remove();
});

As the element #botao_troca_imagem called the event click and you want to remove it within the event itself, just use $(this) to reference the element.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.