Changing the image source using jQuery

前端 未结 16 2058
天命终不由人
天命终不由人 2020-11-22 01:24

My DOM looks like this:

相关标签:
16条回答
  • 2020-11-22 02:06

    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');  
    });
    
    0 讨论(0)
  • 2020-11-22 02:08

    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

    1. 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();  ;
      
    2. 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;
      
    3. 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") ); 
      
    4. 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

    0 讨论(0)
  • 2020-11-22 02:10

    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());
    
    0 讨论(0)
  • 2020-11-22 02:16

    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');
    });
    
    0 讨论(0)
  • 2020-11-22 02:19

    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>
    
    0 讨论(0)
  • 2020-11-22 02:20

    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.

    0 讨论(0)
提交回复
热议问题