我正在编写一个网页,每隔4秒会收到一条不同的消息。我已经构建了一个自定义对象,我打算从中提取信息以创建要显示的字符串。我正在使用类似于Math.random的函数'rand',这将让我随机访问该对象。我将间隔设置为4秒。我可以显示要显示的字符串,但之后网页继续加载并加载并开始滞后以至于我不得不退出。我正在使用的代码如下所示。请帮忙!
var name = "Barack Obama";
var Actions = {
"ActionList" : [
{ "action" : "watches a 30 minute TV show",
"time" : 30,
"time_measure" : "minute",
"assuming" : "assuming he sat through the commercials too"
},
{
"action" : "makes some pizza rolls",
"time" : 9,
"time_measure" : "minute",
"assuming" : "he only made one plateful"
},
{
"action" : "takes a 2 hour nap",
"time" : 2,
"time_measure" : "hour",
"assuming" : "assuming he's a heavy sleeper"
},
{
"action" : "1000 jumping jacks",
"time" : 1,
"time_measure" : "hour",
"assuming" : "he doesn't take a break, or slow down"
}
]
};
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function run() {
/**
* RANDOMLY SELECT OBJECTS
***/
var r = rand(0, 3);
var x = Actions.ActionList[r]["action"];
document.write( x );
}
setInterval(run, 4000);
答案 0 :(得分:0)
加载页面后无法使用document.write。它会破坏当前页面。
你应该使用像appendChild()或innerHTML这样的DOM方法。
答案 1 :(得分:0)
这个JSFiddle有一个工作示例。它与document.write有关。代码中的其他所有内容都能正常运行。