簡體   English   中英

頁面刷新后如何保持onclick功能

[英]How to keep onclick function after page refresh

我是javascript新手,並嘗試編寫代碼,其中兩個不同的按鈕為頁面提供了兩種不同的樣式,以便您可以在開始時選擇一種設計,而網站保持這種狀態。 在刷新站點/單擊同一站點上的其他頁面后,如何使設計保持原樣?

我已經嘗試了sessionStorage和localStorage,但似乎無法正常工作。

這是我到目前為止的內容:

function greenButton() {
 document.getElementById("container").style.backgroundColor = "white";
  document.body.style.backgroundColor = "green";
}
 function redButton() {
  document.getElementById("container").style.backgroundColor = "black";
  document.body.style.backgroundColor = "red";
}

和html:

<div class="green" onclick="greenButton()>green</div>
<div class="red" onclick="redButton()>red</div>

<div class="container">Content</div>

即使刷新/切換頁面后,必須更改/添加什么才能使選定的設計生效?

由於您不熟悉javascript,因此我在這里使用純javascript

創建新函數並在頁面加載時調用它

<body onload="checkthelastColor()">
    <div class="green" onclick="greenButton()>green</div>
    <div class="red" onclick="redButton()>red</div>
    <div class="container">Content</div>
</body>

這是功能

function checkthelastColor(){
    var color = localStorage.getItem("selectedColor")
    if(color == "red"){
        redButton()
    }else{
        greenButton()
    }
}

在您的舊函數中,將顏色保存在localStorage中,例如

function greenButton() {
    document.getElementById("container").style.backgroundColor = "white";
    document.body.style.backgroundColor = "green";
    localStorage.setItem("selectedColor","green");
}
function redButton() {
    document.getElementById("container").style.backgroundColor = "black";
    document.body.style.backgroundColor = "red";
    localStorage.setItem("selectedColor","red");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM