gpt4 book ai didi

javascript - JS 在页面刷新时选择随机引号

转载 作者:太空宇宙 更新时间:2023-11-04 15:52:01 24 4
gpt4 key购买 nike

我正在制作我的网站,我想要这样,每次用户刷新页面时,都会弹出一个新的随机笑话,而不是之前选择的笑话。这是我现在的脚本:

function ShowJoke(){
var Joke=["Jokes", "go", "here"];
var Pick = Math.floor(Math.random() * (Joke.length));
document.write(Joke[Pick]);
}

最佳答案

我只能根据你提供的信息来回答,所以如果有什么不对的地方,请告诉我,这样我就可以解决。

根据我从这个问题中得出的结论,您想在页面加载时加载一个新的笑话。 “每次页面刷新时都会显示一个新的随机报价而不是最后一个”

注意:由于“allow-same-origin”标志,下面的代码片段可能无法工作,除非您使用 XAMPP 之类的东西,否则很可能无法在本地托管。

throwdown是检查cookie是否存在,如果存在,则继续生成,直到生成不等于cookie的新笑话,设置新的cookie,并显示笑话。

// Array of Jokes
var Jokes = [
"I just got fired from my job at the keyboard factory. They told me I wasn't putting in enough shifts.",
"We'll we'll we'll...if it isn't autocorrect.",
"Q. Which type of vegetable tries to be cool, but is only partly successful at it?\n\nA. The radish.",
"The world tongue-twister champion just got arrested. I hear they're gonna give him a really tough sentence."
];

// function to check cookie (true if exists, false if not)
function checkCookie(){
var joke = getCookie();
if (joke != "") {
return true;
} else {
return false;
}
}
// set the cookie so can be referenced later
function setCookie(cvalue){
var cname = "joke";
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// actually acquire the cookie and read it
function getCookie() {
var cname = "joke";
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 "";
}

function ShowJoke(){
let randomNum = ~~(Math.random() * Jokes.length); // pick a random number from 0 to length of jokes
if(checkCookie()){ // check if cookie exists
while(Jokes[randomNum] != getCookie()) randomNum = ~~(Math.random() * Jokes.length);
} // while cookie's joke != generated joke
document.getElementById('Joke').textContent = Jokes[randomNum]; // set content
setCookie(Jokes[randomNum]); // set cookie
}
window.onload = ShowJoke(); // run on window load
<p id="Joke"></p>

关于javascript - JS 在页面刷新时选择随机引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49468425/

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