Programmatically change the src of an img tag

后端 未结 9 1632
执念已碎
执念已碎 2020-11-22 04:31

How can I change the src attribute of an img tag using javascript?


         


        
相关标签:
9条回答
  • 2020-11-22 05:16

    With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with

    document.querySelector('img[name="edit-save"]');
    

    and change the src with

    document.querySelector('img[name="edit-save"]').src = "..."
    

    so you could achieve the desired effect with

    var img = document.querySelector('img[name="edit-save"]');
    img.onclick = function() {
        this.src = "..." // this is the reference to the image itself
    };
    

    otherwise, as other suggested, if you're in control of the code, it's better to assign an id to the image a get a reference with getElementById (since it's the fastest method to retrieve an element)

    0 讨论(0)
  • 2020-11-22 05:22

    You can use both jquery and javascript method: if you have two images for example:

    <img class="image1" src="image1.jpg" alt="image">
    <img class="image2" src="image2.jpg" alt="image">
    

    1)Jquery Method->

    $(".image2").attr("src","image1.jpg");
    

    2)Javascript Method->

    var image = document.getElementsByClassName("image2");
    image.src = "image1.jpg"
    

    For this type of issue jquery is the simple one to use.

    0 讨论(0)
  • 2020-11-22 05:25

    its ok now

    function edit()
    {   
        var inputs = document.myform;
        for(var i = 0; i < inputs.length; i++) {
            inputs[i].disabled = false;
        }
    
        var edit_save = document.getElementById("edit-save");
    
           edit_save.src = "../template/save.png";                              
    }
    
    0 讨论(0)
  • 2020-11-22 05:29

    In this case, as you want to change the src of the first value of your element, you have no need to build up a function. You can change this right in the element:

    <a href='#' onclick='this.firstChild.src="../template/save.png"')'>
      <img src="../template/edit.png" id="edit-save"/>
    </a>
    

    You have several ways to do this. You can also create a function to automatize the process:

    function changeSrc(p, t) { /* where p: Parent, t: ToSource */
      p.firstChild.src = t
    }
    

    Then you can:

    <a href='#' onclick='changeSrc(this, "../template/save.png");'>
      <img src="../template/edit.png" id="edit-save"/>
    </a>
    
    0 讨论(0)
  • 2020-11-22 05:30

    if you use the JQuery library use this instruction:

    $("#imageID").attr('src', 'srcImage.jpg');
    
    0 讨论(0)
  • 2020-11-22 05:31
    <img src="../template/edit.png" name="edit-save" onclick="this.src = '../template/save.png'" />
    
    0 讨论(0)
提交回复
热议问题