,其中 x 表示图像编号 1 或 2。这是可能的还是我必须使用 CSS 来更改图像?" /> ,其中 x 表示图像编号 1 或 2。这是可能的还是我必须使用 CSS 来更改图像?"> ,其中 x 表示图像编号 1 或 2。这是可能的还是我必须使用 CSS 来更改图像?" />
ChatGPT解决这个技术问题 Extra ChatGPT

Changing the image source using jQuery

My DOM looks like this:

<div id="d1">
   <div class="c1">
            <a href="#"><img src="img1_on.gif"></a>
            <a href="#"><img src="img2_on.gif"></a>
   </div>
</div>

When someone clicks on an image, I want the image src to change to <img src="imgx_off.gif"> where x represents the image number 1 or 2.

Is this possible or do I have to use CSS to change the images?

If you want something using jQuery you might want to look into the jQuery Cycle Plugin, demo scrollRight (bottom-right example)
jQuery("#my_image").attr("src", "first.jpg")
You should really accept jonstjohn's answer :) The number of upvotes on both the question and answer indicates a lot of people have run into this. It would improve the question to have an accepted answer.
Till Date, i.e. 19th July, 2016 15:39 PM, Question Upvotes Count 369 And @jonstjohn Answer Upvotes Count 931. But, Such A Bad Luck, @OP Didn't Logged In After Feb 17 '09 at 2:57. :( And, @jonstjohn Answer Remain Unmarked.
Beware that the alt attribute is missing. Especially when used in links, images need an alternative text for assistive technology or the case that the image cannot load, for whatever reason.

A
Andy

You can use jQuery's attr() function. For example, if your img tag has an id attribute of 'my_image', you would do this:

<img id="my_image" src="first.jpg" alt="Insert link 1 alt text here" />

Then you can change the src of your image with jQuery like this:

$("#my_image").attr("src","second.jpg");

To attach this to a click event, you could write:

$('#my_image').on({
    'click': function(){
        $('#my_image').attr('src','second.jpg');
    }
});

To rotate the image, you could do this:

$('img').on({
    'click': function() {
         var src = ($(this).attr('src') === 'img1_on.jpg')
            ? 'img2_on.jpg'
            : 'img1_on.jpg';
         $(this).attr('src', src);
    }
});

C
Community

One of the common mistakes people do when change the image source is not waiting for image load to do afterward actions like maturing image size etc. You will need to use jQuery .load() method to do stuff after image load.

$('yourimageselector').attr('src', 'newsrc').load(function(){
    this.width;   // Note: $(this).width() will not work for in memory images

});

Reason for editing: https://stackoverflow.com/a/670433/561545


Yes. This finally did the trick. .destroy() doesn't go nearly far enough. Nuking all the html and than init again actually works when swapping out images of various sizes and such.
note that load won't fire reliably, especially if the image is in the cache. See the jQuery documentation.
k
kintsukuroi

In case you update the image multiple times and it gets CACHED and does not update, add a random string at the end:

// update image in dom
$('#target').attr('src', 'https://example.com/img.jpg?rand=' + Math.random());

It is very important, at least for me, to add the random string at the end! Tanks!
H
Hassaan

For more information. I try setting src attribute with attr method in jquery for ad image using the syntax for example: $("#myid").attr('src', '/images/sample.gif');

This solution is useful and it works but if changing the path change also the path for image and not working.

I've searching for resolve this issue but not found nothing.

The solution is putting the '\' at the beginning the path: $("#myid").attr('src', '\images/sample.gif');

This trick is very useful for me and I hope it is useful for other.


a
asawyer

IF there is not only jQuery or other resource killing frameworks - many kb to download each time by each user just for a simple trick - but also native JavaScript(!):

<img src="img1_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img1_off.jpg':'img1_on.jpg';">
<img src="img2_on.jpg" 
    onclick="this.src=this.src.match(/_on/)?'img2_off.jpg':'img2_on.jpg';">

This can be written general and more elegant:

<html>
<head>
<script>
function switchImg(img){
    img.src = img.src.match(/_on/) ? 
        img.src.replace(/_on/, "_off") : 
        img.src.replace(/_off/, "_on");
}
</script>
</head>
<body>
    <img src="img1_on.jpg" onclick="switchImg(this)">
    <img src="img2_on.jpg" onclick="switchImg(this)">
</body>
</html>

It always surprises me how many people can't read a question and give the answer requested. It seemed obvious to me (and you) that the question was looking for a generic solution which is why the OP gave 2 examples. And yet everyone else seemed to not only totally miss it but give an answer that didn't even answer the question. :(
P
Peter Ajtai

I'll show you how to change the image src, so that when you click an image it rotates through all the images that are in your HTML (in your d1 id and c1 class specifically)... whether you have 2 or more images in your HTML.

I'll also show you how to clean up the page after the document is ready, so that only one image is displayed initially.

The full code

$(function() {

    var $images = $("#d1 > .c1 > a").clone();  

    var $length = $images.length;
    var $imgShow = 0;

    $("#d1 > .c1").html( $("#d1 > .c1 > a:first") );  

    $("#d1 > .c1 > a").click(function(event) { 

        $(this).children().attr("src", 
                        $("img", $images).eq(++$imgShow % $length).attr("src") );
        event.preventDefault();

    });
});

The breakdown

Create a copy of the links containing the images (note: you could also make use of the href attribute of the links for added functionality... for example display the working link below each image): var $images = $("#d1 > .c1 > a").clone(); ; Check how many images were in the HTML and create a variable to track which image is being shown: var $length = $images.length; var $imgShow = 0; Modify the document's HTML so that only the first image is being shown. Delete all the other images. $("#d1 > .c1").html( $("#d1 > .c1 > a:first") ); Bind a function to handle when the image link is clicked. $("#d1 > .c1 > a").click(function(event) { $(this).children().attr("src", $("img", $images).eq(++$imgShow % $length).attr("src") ); event.preventDefault(); }); The heart of the above code is using ++$imgShow % $length to cycle through the jQuery object containing the images. ++$imgShow % $length first increases our counter by one, then it mods that number with how many images there are. This will keep the resultant index cycling from 0 to length-1, which are the indices of the $images object. This means this code will work with 2, 3, 5, 10, or 100 images... cycling through each image in order and restarting at the first image when the last image is reached. Additionally, .attr() is used to get and set the "src" attribute of the images. To pick elements from among the $images object, I set $images as the jQuery context using the form $(selector, context). Then I use .eq() to pick just the element with the specific index I'm interested in.

jsFiddle example with 3 images


You can also store the srcs in an array.
jsFiddle example with 3 images

And here's how to incorporate the hrefs from the anchor tags around the images:
jsFiddle example


M
Mohammad

Hope this can work

<img id="dummyimage" src="http://dummyimage.com/450x255/" alt="" />
<button id="changeSize">Change Size</button>
$(document).ready(function() {
    var flag = 0;
    $("button#changeSize").click(function() {
        if (flag == 0) {
            $("#dummyimage").attr("src", "http://dummyimage.com/250x155/");
            flag = 1;
        } else if (flag == 1) {
            $("#dummyimage").attr("src", "http://dummyimage.com/450x255/");
            flag = 0;
        }
    });
});

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
Thanks Derek will keep this thing in my mind from next time onwards
M
Mr Bitmap

You should add id attribute to your image tag, like this:

<div id="d1">
   <div class="c1">
            <a href="#"><img id="img1" src="img1_on.gif"></a>
            <a href="#"><img id="img2" src="img2_on.gif"></a>
   </div>
</div>

then you can use this code to change the source of images:

 $(document).ready(function () {
        $("#img1").attr({ "src": "logo-ex-7.png" });
        $("#img2").attr({ "src": "logo-ex-8.png" });
    });

F
FernandoEscher

You can also do this with jQuery in this way:

$(".c1 img").click(function(){
     $(this).attr('src','/new/image/src.jpg');   
});

You can have a condition if there are multiple states for the image source.


this syntax is not right. the jquery attr() function takes 1 or 2 params. The first being a string with the HTML attribute name, the second being the value for that attribute that you want to set.
K
Kayvan Tehrani

I had the same problem when trying to call re captcha button. After some searching, now the below function works fine in almost all the famous browsers(chrome,Firefox,IE,Edge,...):

function recaptcha(theUrl) {
  $.get(theUrl, function(data, status){});
  $("#captcha-img").attr('src', "");
  setTimeout(function(){
       $("#captcha-img").attr('src', "captcha?"+new Date().getTime());
  }, 0);
 }

'theUrl' is used to render new captcha image and can be ignored in your case. The most important point is generating new URL which forces FF and IE to rerender the image.


M
MasterAler

Change the image source using jQuery click()

element:

    <img class="letstalk btn"  src="images/chatbuble.png" />

code:

    $(".letstalk").click(function(){
        var newsrc;
        if($(this).attr("src")=="/images/chatbuble.png")
        {
            newsrc="/images/closechat.png";
            $(this).attr("src", newsrc);
        }
        else
        {
            newsrc="/images/chatbuble.png";
            $(this).attr("src", newsrc);
        }
    });

N
Neil Meyer

I made a codepen with exactly this functionality here. I will give you a breakdown of the code here as well.

Codepen

$(function() { //Listen for a click on the girl button $('#girl-btn').click(function() { // When the girl button has been clicked, change the source of the #square image to be the girl PNG $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/girl.png"); }); //Listen for a click on the plane button $('#plane-btn').click(function() { // When the plane button has been clicked, change the source of the #square image to be the plane PNG $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/airplane.png"); }); //Listen for a click on the fruit button $('#fruits-btn').click(function() { // When the fruits button has been clicked, change the source of the #square image to be the fruits PNG $('#square').prop("src", "https://homepages.cae.wisc.edu/~ece533/images/fruits.png"); }); });

Source of Images


A
Anyone_ph

I have the same wonder today, I did on this way :

//<img src="actual.png" alt="myImage" class=myClass>
$('.myClass').attr('src','').promise().done(function() {
$(this).attr('src','img/new.png');  
});

R
Raymond Wachaga

This is a guaranteed way to get it done in Vanilla (or simply Pure) JavaScript:

var picurl = 'pictures/apple.png';
document.getElementById("image_id").src=picurl;

S
Szél Lajos

Just an addition, to make it even more tiny:

$('#imgId').click(function(){
    $(this).attr("src",$(this).attr('src') == 'img1_on.gif' ? 'img1_off.gif':'img1_on.gif');
});

C
Community

Short but exact

$("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );

let pic=[ "https://picsum.photos/id/237/40/40", // arbitrary - eg: "img1_on.gif", "https://picsum.photos/id/238/40/40", // arbitrary - eg: "img2_on.gif" ]; $("#d1 img").click(e=> e.target.src= pic[e.target.src.match(pic[0]) ? 1:0] );


A
Abrar Jahin

There is no way of changing the image source with CSS.

Only possible way is using Javascript or any Javascript library like jQuery.

Logic-

The images are inside a div and there are no class or id with that image.

So logic will be select the elements inside the div where the images are located.

Then select all the images elements with loop and change the image src with Javascript / jQuery.

Example Code with demo output-

$(document).ready(function() { $("button").click(function() { $("#d1 .c1 a").each(function() { $(this).children('img').attr('src', 'https://www.gravatar.com/avatar/e56672acdbce5d9eda58a178ade59ffe'); }); }); });