简体   繁体   English

javascript简单的随机游戏

[英]javascript simple random game

im just starting out with javascript so go ez on me. 我刚刚开始使用javascript,所以请关注我。 i have an exercise where i have to create 4 divs that are a box's. 我有一个练习,我必须创建4个盒子的div。 and each time you refresh the page one div is the correct one to select. 每次刷新页面时,一个div是正确的选择。 the main question im wondering is how can match a div to random number ? 我想知道的主要问题是如何将div与随机数相匹配?

my divs in the html are as follows 我的html中的div如下

<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>

for javascript all i have so far is 我迄今为止所有的javascript都是

var randomNumber = Math.ceil(Math.random()*4);

but im not sure how i can make a function to say if randomNumber == div# ? 但我不知道如何使函数说出randomNumber == div# then do this. 然后这样做。

document.getElementById('div' + randomNumber);

That should do it. 应该这样做。 Then you can set all the properties on the element that you need from there. 然后,您可以从那里设置所需元素的所有属性。


If you need to do anything complicated, I would take a different approach, make the divs of a specific class to select from, and utilize jQuery. 如果你需要做任何复杂的事情,我会采取不同的方法,使特定类的div可供选择,并利用jQuery。 This was asked last week, and you can find my answer that also applies to your specific question here: https://stackoverflow.com/a/9450352/362536 这是上周被问到的,你可以在这里找到我的答案也适用于你的具体问题: https//stackoverflow.com/a/9450352/362536

All right so you have four divs as you explained. 好的,所以你解释时有四个div。 We're going to want to add code to them that processes the user's clicks so we'll add what's called an event handler to them. 我们将要为他们添加处理用户点击的代码,以便我们为他们添加所谓的事件处理程序

<div id="div1" onclick="process(1)"></div>
<div id="div2" onclick="process(2)"></div>
<div id="div3" onclick="process(3)"></div>
<div id="div4" onclick="process(4)"></div>

Now in a script tag above these divs in the code put the following function: 现在在代码中上面的脚本标记中放入以下函数:

function ( divNum ) {
    // Define box as the div on which the user clicked
    var box = document.getElementById('div' + divNum);

    // Compare the div the user clicked on to the random number
    if ( divNum === randomNumber ) {
        // The user chose right
        box.style.backgroundColor = "black";
    }
    else {
        // The user chose incorrect
        box.style.backgroundColor = "red";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM