Javascript 在页面加载时更改图像的src

Javascript 在页面加载时更改图像的src,javascript,jquery,html,Javascript,Jquery,Html,我正在尝试更改图像的src,一旦它被更改为在整个网站上保持这样 <img id="profile" src="profilePicture.jpg"> <input type="text" name="image" id="imgLink"> <button type="button" id="upload">Upload</button> 如您所见,我试图将图像的链接存储在全局变量(var link)中,在函数内部更改图像的src,然后在外部再

我正在尝试更改图像的
src
,一旦它被更改为在整个网站上保持这样

<img id="profile" src="profilePicture.jpg">
<input type="text" name="image" id="imgLink">
<button type="button" id="upload">Upload</button>
如您所见,我试图将图像的链接存储在全局变量(var link)中,在函数内部更改图像的
src
,然后在外部再次更改,以便页面在加载图像时加载图像

更改图像的
src
可以工作,但一旦我刷新页面或转到另一个页面并返回,图像将不再更改


如何使整个网站保持不变

通常您会在服务器端执行此操作,因为客户端解决方案只在用户使用的一个浏览器上工作

$(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);   
});

全局变量存在于
$(document).ready()
函数之外。我是jQuery新手,我的问题是链接变量在该函数之外没有值。单击(函数(){..因为我试图在var链接中放置一个指向图像的链接,然后只更改图像的src,这是可行的。但是,当通过输入提供链接时,我需要它工作。使用cookies在页面刷新和页面导航之间存储URL。或者服务器端脚本就可以了。当你请求不获得投票时,通常情况下我并不是在乞求不要获得否决票,我只是在努力寻找我自己搞不清楚的问题的答案。我只是在问那些可能想否决投票的人,他/她为什么会这样做,这样我将来在问更多的问题时,我就会知道,或者在这个问题上更加明确。
$(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);   
});