Javascript change image, href onclick = looking for the easiest way

What is the easiest way to change src image when i click on href -with jquery?
img id="my_image" class="icon" src="1.png" alt="1.png" border="0" />
< a href="#" id="1">
< a href="#" id="2">
< a href="#" id="3">
1.png, 2.png, 3.png

Href is ok C # or would it be better to do some JS here?

+4
source share
4 answers

You should .bind() help a .click() help an event listener at your anchors. In this listener, you change the src attribute by calling .attr() help

 $('a').click(function(event) { $('#my_image').attr('src', function(i, src) { return event.target.id + '.png'; }); return false; }); 
+4
source
 <img id="my_image" class="icon" src="1.png" alt="1.png" border="0" /> <a onclick="changeImage(this)" href="#" id="1">1</a> <a onclick="changeImage(this)" href="#" id="2">2</a> <a onclick="changeImage(this)" href="#" id="3">3</a> <script> function changeImage(thisDiv){ document.getElementById('my_image').src = thisDiv.id+".png" } </script> 

Edit: didn't see jQuery requirements!

+3
source

This should work:

 <a href="javascript:$('#my_image').attr('src', '2.png');" id="1"> 
+2
source
 $('a').click(function(e) { var id = this.id; $('#my_image').attr('src', id + '.png'); e.preventDefault(); }); 
+2
source

Source: https://habr.com/ru/post/1337464/


All Articles