简体   繁体   English

页面加载时更改图像的src

[英]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. 我正在尝试更改图片的src ,并且一旦更改为在整个网站上都保持不变。

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

jQuery: 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. 如您所见,我尝试将图像的链接存储在全局变量(var link)中,在函数内部更改图像的src ,然后在外部再次更改它,以便页面在加载时加载图像。

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. 更改图像的srcsrc的,但是一旦刷新页面或转到另一页面并返回,图像将不再更改。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM