简体   繁体   中英

Change the src of an image when the page loads

I am trying to change the src of an image and once it was changed to remain like that over the whole website.

<img id="profile" src="profilePicture.jpg">
<input type="text" name="image" id="imgLink">
<button type="button" id="upload">Upload</button>

jQuery:

$(document).ready(function () { 
    var link;
    $("#upload").click(function (){
        link = $("#imgLink").val();
        $("#profile").prop('src', link);
    });
    $("#profile").prop('src', link);   
  });

As you can see I tried to store the link of the image in a global variable( var link ) , change the src of the image inside the function and then change it once again outside so that the page loads the image when it's loaded.

Changing the src of the image works but once I refresh the page or go to another page and come back, the image is not changed any more.

How can I make it to remain changed over the whole website?

Normally you would do this on the serverside since a clientside solution only works on the one browser the user is using.

$(function () { 
    //read localstorage
    var link = localStorage.getItem("myImage") || ""; //change "" to default value
    $("#upload").click(function (){
        link = $("#imgLink").val();
        $("#profile").prop('src', link);
        localStorage.setItem("myImage", link); //set localstorage with new value. 
    });
    $("#profile").prop('src', link);   
});

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