乍一看,其他的答案不處理頁面加載(也許他們做的和我想的東西.. )。 localStorage或者cookies都可以,但是你選擇這個問題並沒有太大的區別。你應該嘗試兩種,只是爲了練習。
我添加了一個刪除Cookies按鈕,爲您提供方便(編輯:它不刪除cookie,只需將其設置爲空字符串)
<script>
// either we can read a cookie
// or the cookie is empty -> then we pick a random name and set is as cookie
window.onload = function() {
var randomname = getCookie('randomname');
if(randomname != '') {
setName(randomname);
}
else {
setCookie('randomname', replaceName());
}
}
function replaceName() {
var textArray = ['Mark', 'Jane', 'Aldrin', 'Len'];
var randomIndex = Math.floor(Math.random() * textArray.length);
var randomElement = textArray[randomIndex];
setName(randomElement);
return randomElement; // we would like to know the name, just the name, so we can store it somewhere
}
// I take this code out of replaceName() and set it in a separate function.
// so you can use it both for setting the name from cookie as for the random name
function setName(name) {
var text1 = "Hi, I'm ";
var text2 = ", How can i help you?";
var text3 = text1.concat(name, text2);
document.getElementById("demo").innerHTML = text3;
}
function deleteCookies() {
setCookie('randomname', '');
}
// Get and Set cookie; @see https://www.w3schools.com/js/js_cookies.asp
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
</script>
<div id="demo"></div>
<input type="button" value="delete cookie" onclick="deleteCookies()"/>
我會建議:儘量使用更好的功能名稱;確保函數的名稱能夠描述你打算做什麼。 你注意到我把你的功能削減了一半,我做了兩個功能。由於兩個新名稱,併爲保存在cookie或localStorage的名字是需要的setName,最好是把它作爲一個單獨的函數
嘗試的localStorage –
是,本地或會話存儲可以讓您保存價值,可以是保留在頁面加載作爲一種保存方法https://www.w3schools.com/html/html5_webstorage.asp –
[本地存儲/會話存儲](https://stackoverflow.com/questions/5523140/html5-local-存儲-VS-會話存儲) – Totoro