按钮,改变一个变量,并创建一个新的按钮
问题描述:
我试图做一些基于文本的游戏,但使用按钮而不是文本输入。例如,我想从一个页面上的3个按钮开始。当你选择其中一个按钮时,函数应该改变这个问题变量,然后为下一个问题创建按钮。按钮,改变一个变量,并创建一个新的按钮
问题一:
<DOCTYPE html>
<body>
<button onclick="russetPotato()">Russet</button>
<button onclick="redPotato()">Red</button>
<button onclick="sweetPotato()">Sweet</button>
</body>
<script type="text/javascript">
var seed = 0;
var soil = 0;
function russetPotato(){
seed = 1
document.write("You set seed as Russet Potato.");
}
function redPotato(){
seed = 2
document.write("You set seed as Red Potato.");
}
function sweetPotato(){
soil = 3
document.write("You set seed as Sweet Potato.");
}
</script>
</html>
现在我想要做的就是添加的第二个问题。在种子按钮被回答后,我可以如何让土壤按钮出现,而不是同时出现?
<DOCTYPE html>
<body>
<button onclick="russetPotato()">Russet</button>
<button onclick="redPotato()">Red</button>
<button onclick="sweetPotato()">Sweet</button>
<button onclick="sandySoil()">Thin Sandy Soil</button>
<button onclick="loamSoil()">Loose Loam Soil</button>
<button onclick="claySoil()">Heavy Clay Soil</button>
</body>
<script type="text/javascript">
var seed = 0;
var soil = 0;
function russetPotato(){
seed = 1
document.write("You set seed as Russet Potato.");
}
function redPotato(){
seed = 2
document.write("You set seed as Red Potato.");
}
function sweetPotato(){
soil = 1
document.write("You set seed as Sweet Potato.");
}
function sandySoil(){
soil = 1
document.write("You set soil as Thin Sandy Soil.");
}
function loamSoil(){
soil = 2
document.write("You set soil as Loose Loam Soil.");
}
function claySoil(){
soil = 3
document.write("You set soil as Heavy Clay Soil.");
}
</script>
</html>
道歉,如果这其实很简单。这是我第一次使用javascript/html进行实验。
答
您不必创建新按钮(如果您始终使用其中的三个按钮)。无论如何,这取决于所有的游戏逻辑。
它通常是如何做的是使用对象的数组文本,如:
var stages = [
[
{btntext:"Russet", type:"seed", pts:1, text:"You set seed as Russet Potato."},
{btntext:"Red", type:"seed", pts:2, text:"You set seed as Russet Potato."},
{btntext:"Sweet", type:"soil", pts:1, text:"You set seed as Russet Potato."}
],[
{btntext:"Sand", type:"foo", pts:1, text:"You set soil as Thin Sandy Soil."},
{btntext:"Loam", type:"bar", pts:2, text:"You set soil as Loose Loam Soil."},
{btntext:"Clay", type:"bar", pts:3, text:"You set soil as Heavy Clay Soil."}
],[
{btntext:"Baz", type:"baz", pts:1, text:"You set Baz!."},
{btntext:"Foo2", type:"foo", pts:2, text:"You set Foo twice!."}
]
];
现在,如果你看一下上面的阵列做:alert(stages.length) // 3
你会看到,你可以指望3
阶段。如果设置了var counter = 0
最初0
你可以先阅读0
索引阶段,阅读长阶段的选项像var nOfBtns = stages[counter].length; // 3
因为你有三个选择黄褐色红甜。最后一个会返回你2个按钮。您可以从阵列中提取所需的所有值和对象真的很容易,如:
var selectedButtonPoints = stages[counter][buttonNid].pts;
当玩家点击按钮,你提取您的阵列中的所有需要的信息,你只需创建一个新的集视按钮在下一阶段的项目数量和增加计数器counter += 1;
只是给你一个想法。
此外,document.write已弃用。请参阅如何使用innerHTML
来代替。
设置一些网页元素的像一些容器:
<div id="buttons"></div> <!-- JS will populate with needed buttons -->
<div id="points"></div> <!-- JS will write here the player stats -->
<!-- etc... -->
目标与JS这些元素,创造功能,如function createNewButtons()
,并利用它们来填充按钮和信息的元素。
您不能在结尾处的'