【发布时间】:2016-07-21 18:46:35
【问题描述】:
我是 JavaScript 新手,我有一个问题,代码如下所示:
function job1() {
var subText1="";
var subText2="";
var text="";
var vocabulary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz0123456789";
// Use the delay function to create a full text in 20 * 150 milliseconds
var i = 0,
action = function() {
var temp = vocabulary.charAt(Math.floor(Math.random() * vocabulary.length));
text+= temp;
document.write(text + "<br>");
i++;
if (i < 20) {
setTimeout(action, 150);
} else {
// The first subText is from position 0 until some random number random between 0 and the text length
subText1 = text.slice(0, Math.floor(Math.random() * text.length));
// The second subText is from where the first subText ends until the last character form the text input
subText2 = text.slice(subText1.length, text.length);
// output of the subText1 and the subText2 for the first time
document.write("subText1: " + subText1 + "<br>");
document.write("subText2: " + subText2 + "<br>");
document.write("text: " + text + "<br>");
}
};
setTimeout(action, 0);
// output of the subText1 and the subText2 once more
document.write("subText1: " + subText1 + "<br>");
document.write("subText2: " + subText2 + "<br>");
// NextJob: job2, job3
// job dependency
var nextJob = "job2, job3";
var prevJob = "null";
// results
return {
subText1_RT : subText1,
subText2_RT : subText2
};
}
我的问题是我需要将subText1 和subText2 从action = function().... 部分获取到此部分:
return {
subText1_RT : subText1,
subText2_RT : subText2
};
但是subText1 和subText2 变量是空的。
代码如下:http://jsfiddle.net/TalGoz/4tgc372e/
看起来job1() 函数的所有部分都在action = function() 部分之前执行。让它像这样作为函数内部的函数工作是非常重要的,我不能为了我的目标而分离这些函数。
希望这里有人能帮我看看问题并解决它。
【问题讨论】:
-
setTimeout和return,一起用没意义。
-
@epascarello 为什么?我在这里使用它没有看到任何问题。如果使用正确,
document.write没有任何问题。问题是滥用,而不是不使用。 -
OP 正在运行 setTimeout 和 document.write,它将替换页面内容。在这里使用不当,99% 的情况下使用是错误的。
-
@epascarello document.write 只是为了查看输出。
-
您不能从异步方法返回。完成后,您需要使用回调来执行最后的步骤。
标签: javascript jquery