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

时间:2019-02-22 20:21:38

标签: javascript html css

我是一名学生,对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>

1 个答案:

答案 0 :(得分:0)

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

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>