我正在使用一个jQuery脚本,它在页面加载时显示来自数组的随机口号。 但是我希望这个口号每6秒更换一次。我怎么能这样做?
This is a working fiddle以下是代码:
$(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);
});
答案 0 :(得分: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);
}
更新:投入两行,防止连续两次重复相同的短语,以便进行衡量。
答案 1 :(得分:0)
这将无限次更改短语,但您必须使用Jquery Timers插件。
$(document).everyTime(1000, function(i) {
var phrase = phrases[Math.floor(Math.random()*phrases.length)]
$('#site').text(phrase);
}, 0);