I am using a jQuery script that shows a random slogan from an array on page load. However I want this slogan to be changed every 6 sec. How can I do this?
我正在使用一个jQuery脚本,它在页面加载时显示一个数组的随机口号。但是我希望这个口号每6秒更换一次。我怎样才能做到这一点?
This is a working fiddle and here is the code:
这是一个工作小提琴,这里是代码:
$(document).ready(function () {
phrases = [
"a creative Chicago design shop",
"design is simple",
"we build fine, fine things",
"we love creating"
];
var phrase = phrases[Math.floor(Math.random()*phrases.length)]
$('#site').text(phrase);
});
2 个解决方案
#1
1
$(document).ready(function () {
changePhrase();
var rotate = setInterval(changePhrase, 6000);
});
function changePhrase() {
phrases = [
"a creative Chicago design shop",
"design is simple",
"we build fine, fine things",
"we love creating"
];
currentPhrase = $('#site').text();
if (phrases.indexOf(currentPhrase)) phrases.splice(phrases.indexOf(currentPhrase), 1); // remove current phrase from array to prevent repetitions
var phrase = phrases[Math.floor(Math.random()*phrases.length)]
$('#site').text(phrase);
}
Update: Thrown in a two-liner that prevents repetition of the same phrase two times in a row for good measure.
更新:抛出一个双线,防止连续两次重复相同的短语,以获得良好的衡量标准。
#2
0
this will change phrases for an infinite number of time , but you have to use the Jquery Timers Plugin .
这将无限次更改短语,但您必须使用Jquery Timers插件。
$(document).everyTime(1000, function(i) {
var phrase = phrases[Math.floor(Math.random()*phrases.length)]
$('#site').text(phrase);
}, 0);
#1
1
$(document).ready(function () {
changePhrase();
var rotate = setInterval(changePhrase, 6000);
});
function changePhrase() {
phrases = [
"a creative Chicago design shop",
"design is simple",
"we build fine, fine things",
"we love creating"
];
currentPhrase = $('#site').text();
if (phrases.indexOf(currentPhrase)) phrases.splice(phrases.indexOf(currentPhrase), 1); // remove current phrase from array to prevent repetitions
var phrase = phrases[Math.floor(Math.random()*phrases.length)]
$('#site').text(phrase);
}
Update: Thrown in a two-liner that prevents repetition of the same phrase two times in a row for good measure.
更新:抛出一个双线,防止连续两次重复相同的短语,以获得良好的衡量标准。
#2
0
this will change phrases for an infinite number of time , but you have to use the Jquery Timers Plugin .
这将无限次更改短语,但您必须使用Jquery Timers插件。
$(document).everyTime(1000, function(i) {
var phrase = phrases[Math.floor(Math.random()*phrases.length)]
$('#site').text(phrase);
}, 0);