简体   繁体   中英

Change image on click with jQuery

Sorry about the vague title but I'm not really sure how to describe this.

What I want to do is onclick, change the image. Here is that portion of the code.

Can someone tell me if this is possible? I don't see a way to do this because I'm not sure how to reference the anchor tag.

$(document.createElement('a'))
  .attr('href', '#')
  .html('<img src="myimage.jpg" />')
  .click( function( e ){
    // When the user clicks the anchor tag above, I want to replace the current
    // image (myimage.jpg) with another one.
  }

Assuming you want to retain the state of the code in which it is written (which is horrible), e.currentTarget is a reference to the element that is being clicked. You can use that to repeat your (discouraged) .html() procedure with another image URL.

$(document.createElement('a'))
    .attr('href', '#')
    .html('<img src="myimage.jpg" />')
    .click( function( e ){
        $(e.currentTarget).html('<img src="myimage2.jpg" />');
    });

The easiest way is just to give the image a class, like, "myImg", and use the .on() method to bind to dynamically created elements

$(document).on('click', '.myImg', function(){
    //$(this) refers to the image that we clicked
    $(this).prop('src', 'http://my-domain.com/path/to/my/new-image.jpg');
});

This binds the event to the document, and anytime an image with the class of "myImg" is clicked, it will replace the image.

$(document.createElement('a'))
  .attr('href', '#')
  .html('<img src="myimage.jpg" />')
  .click( function( e ){
      $(this).find('img').attr('src','myNewImage.jpg');
  });
}
//create node
$('<a>', {
   'href': '#',
   'src': 'myimage.jpg'
})

//add it to the body
.appendTo('body')

//add envent
.on('click', function(){
   $(this).attr('src', 'otherimage.jpg');

   //prevent to jump to the top of the page caused by the '#'
   return false;
});

Use this simple one

$('img').click(function () {
 $(this).attr('src', 'src/to/new/file.png');
}

If you want to change the image when click is over the a . Then use

$('a').click( function () {

instead of the image one.

That will change the src attribute of the current image.

Here is a working fiddle for this :)

http://jsfiddle.net/afzaal_ahmad_zeeshan/8H4MC/

You will se when the mouse is hovered over the image, it changes. You can use click instead of hover . That should work. And don't create a if you have to disable it using href="#" .

If you want a cursor of pointer use cursor: pointer in CSS or use

$(this).css('cursor', 'pointer');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM