如何使用DOM和JavaScript在3个不同级别的游戏之间切换?例如。简单,中等和困难

时间:2011-05-14 22:13:22

标签: javascript dom

我正在尝试使用DOM和JavaScript制作一个简单的游戏,在这个游戏中我有3个不同的级别:简单,中等和难度。默认情况下,当页面加载时,使用简单级别!但我希望能够使用javascript在3个不同级别之间切换!

可以使用javascript cookie会话执行此操作,因此在单击按钮时正在使用/激活特定功能,然后使用该功能直到用户单击另一个按钮,例如中等级别。 / p>

例如:

function easylevel() {
}

function mediumlevel() {
}

function hardlevel() {
}

因此,通过单击按钮激活上述任何功能并将其存储到cookie会话中,例如:

<input type="button" onclick="easylevel()" value="Easy Level" />
<input type="button" onclick="mediumlevel()" value="Medium Level" />
<input type="button" onclick="hardlevel()" value="Hard Level" />

我已经尝试了这个,但它不起作用,有人可以解释一下我哪里出错了!我200%肯定我错了,因为我对JS不太了解,所以需要帮助和建议!

1 个答案:

答案 0 :(得分:1)

如果您想要的是重复调用函数,那么您可以使用setInterval

<script>
var intervalInMilliseconds = 1000; // change this to watever value you like
var activeInterval = undefined;
function startEasyLevel() {
    if (activeInterval) {
         clearInterval(activeInterval);
    }
    activeInterval = setInterval(easylevel, intervalInMilliseconds);
}
function startMediumLevel() {
    if (activeInterval) {
         clearInterval(activeInterval);
    }
    activeInterval = setInterval(mediumlevel, intervalInMilliseconds);
}
function startHardLevel() {
    if (activeInterval) {
         clearInterval(activeInterval);
    }
    activeInterval = setInterval(hardlevel, intervalInMilliseconds);
}
</script>

<input type="button" onclick="startEasyLevel()" value="Easy Level" />
<input type="button" onclick="startMediumLevel()" value="Medium Level" />
<input type="button" onclick="startHardLevel()" value="Hard Level" />

将此当前级别函数添加到此,它应该每秒调用该函数。单击其中一个按钮后,它将立即停止调用当前级别功能并继续调用与单击按钮关联的功能。

如果您希望默认加载某个级别,可以使用window元素的onload事件:

window.onload = startEasyLevel;