过去几天,我和我的 friend 们在开发应用程序方面获得了很大的乐趣,唯一的问题是我们都不懂 JavaScript。到目前为止一切都很顺利。我从谷歌搜索中学到了很多东西,但我似乎无法解决这个问题。所以我们有一个调用函数的下拉菜单,
select id="vg" class="dropdown" onchange="vgchosen.call(this, event)">
这让我们回到了名为 vgchosen 的函数。在此函数中,有一个 switch 方法可以帮助评估所选的下拉菜单选项。
function vgchosen(event) {
alert(this.options[this.selectedIndex].text);
var vgc = document.getElementById("vg").selectedIndex;
var y = document.getElementById("vg").options;
switch (y[vgc].text) {
case "Action":
var actionvgc = [
"You should play |Skyrim",
"You should play |Killing Floor 2",
"You Should play |Counter Strike Global Offensive",
"You should play |Left 4 Dead",
"You should play |House of the Dead",
"You should play |Elite: Dangerous",
"You should play |Middle Earth: Shadow of Mordor",
"You should play |Crypt of the Necro Dancer",
"You should play |The Witcher 3: Wild Hunt",
"You should play |Dark Souls",
];
setInterval(function() {
var i = Math.round((Math.random()) * actionvgc.length);
if (i == actionvgc.length) --i;
$("#actionvgc").html(actionvgc[i]);
}, 1 * 1000);
break;
case "Shooter":
var shootervgc = [
"You should play |Skyri",
"You should play |Killing Floor ",
"You Should play |Counter Strike Global Offensiv",
"You should play |Left 4 Dea",
"You should play |House of the Dea",
"You should play |Elite: Dangerou",
"You should play |Middle Earth: Shadow of Mordo",
"You should play |Crypt of the Necro Dance",
"You should play |The Witcher 3: Wild Hun",
"You should play |Dark Soul",
];
setInterval(function() {
var i = Math.round((Math.random()) * shootervgc.length);
if (i == shootervgc.length) --i;
$("#actionvgc").html(shootervgc[i]);
}, 1 * 1000);
break;
}
}
当您通过选项选择启动该功能时,一切正常,您每秒都会给出一个新的游戏创意。当你想切换到不同的选项时,问题就出现了。如果您选择射击游戏(游戏的区别在于最后一个字母都丢失了),它将同时显示两个游戏创意。当新循环开始时如何停止第一个循环?
编辑:#actionvgc 是显示文本的位置。可以在这里看到
<div id="actionvgc">"Hello World! im FLi!"</div>
最佳答案
setInterval()
函数返回一个标识该特定计时器的值。您可以稍后使用 clearInterval()
来停止它。
var timerId; // should probably be global
// ...
clearInterval(timerId); // clear prev timer
timerId = setInterval(function() { /* ... */ }, 1000);
关于javascript - 停止 switch 方法内的嵌套 if 循环 | JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29898816/