gpt4 book ai didi

javascript - 每次用户访问页面时如何显示新图像

转载 作者:可可西里 更新时间:2023-11-01 14:59:34 26 4
gpt4 key购买 nike

我是一名学生,对 JS 还很陌生。每次用户重新访问页面时,我都需要在页面上显示新的广告图片。我正在考虑将 img src 路径存储在一个数组中。我已经让它工作了,但代码不是很有效。谁能告诉我如何改进我的代码以及更好的方法是什么?谢谢。

var content = document.getElementById("advert-content");

//storing the ads img src into an array
var adverts = ["Assets/pineapple.jpg", "Assets/conf.jpg", "Assets/balloonsad.jpg"];


function getRand() {
return Math.floor(Math.random() * Math.floor(3));
}

function setAd(){
//check if the localstorage add exists and
if (localStorage.ad == 0){
content.setAttribute("src", adverts[1]);
}
else if (localStorage.ad == 1) {
content.setAttribute("src", adverts[2]);
}
else if (localStorage.ad == 2) {
content.setAttribute("src", adverts[0]);
}
}

function update(){
// if nothing is stored in the local storage display the first advert image
if (!localStorage.ad){
content.setAttribute("src", adverts[0]);
}
else {
setAd();
let randnum = getRand();
//get a different number than the one stored inside the local storage

while (randnum == localStorage.ad) {
randnum = getRand();
}
// update the image with a different number
localStorage.ad = adverts.indexOf(adverts[randnum]);
}
}

//call function
update();
 <section id = "adverts">
<img id="advert-content"/>
</section>

最佳答案

以下是对您的代码的一些改进:

var storage = 'localStorage'; // we can change between storages if required
var adLabel = 'ad'; // another string we might need to update someday

var content = document.getElementById("advert-content");

//storing the ads img src into an array
var adverts = ["https://placeholdit.imgix.net/~text?txtsize=63&bg=F64&txtclr=fff&txt=Image-2", "https://placeholdit.imgix.net/~text?txtsize=63&bg=F64&txtclr=fff&txt=Image-3", "https://placeholdit.imgix.net/~text?txtsize=63&bg=F64&txtclr=fff&txt=Image-4"];


function getRand(a) {
// let's use the array length to avoid updating this function
return Math.floor(Math.random() * Math.floor(a.length));
}

function setAd(adNum){
// just set the src and storage value
content.setAttribute("src", adverts[adNum]);
// save only the index instead of the whole url string
window[storage].setItem(adLabel, adNum);
}

function update(){
let randNum;
//get a different number than the one stored inside the local storage
let localStorageAd = window[storage].getItem(adLabel);
do {
randNum = getRand(adverts);
} while (randNum == localStorageAd)
// update the image with a different number
setAd(randNum);
}

//call function
update();
<section id = "adverts">
<img id="advert-content" src="https://placeholdit.imgix.net/~text?txtsize=63&bg=F64&txtclr=fff&txt=Image-1"/>
</section>

关于javascript - 每次用户访问页面时如何显示新图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54834628/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com