儿童的Javascript游戏

时间:2012-12-25 22:26:20

标签: javascript html getelementbyid

我正在尝试用javascript制作游戏。我的代码中仍然有很多问题。代码应该有2个按钮;一个用于改组图像骰子和一个按钮,以检查孩子是否写了正确的答案。

  • 2个按钮
  • 1个文本框
  • 以及显示答案是否正确的地方

这是我的代码。

我不知道为什么当我把document.getElementbyID(“test”)的来源放在什么都没有 因为我希望每次点击开始都会选择随机图像。

我很感激任何帮助,因为我还是javascript的初学者。

  <head> 

<script type="text/javascript">


function startf(){
var images = []; 
index = 0;
images[0] = "<img src='1.png' length=70px width=75px>";
images[1] = "<img src='2.png' length=70px width=75px>";
images[2] = "<img src='3.png' length=70px width=75px>";
images[3] = "<img src='4.png' length=70px width=75px>";
index = Math.floor(Math.random() * images.length);
take(index);

function take(ind)
{
return document.getElementbyId("ind")="What should i put here";
}
}
function check(){
var ch=getElementbyId("answer").value;
if (ch=index+1)
{
document.getElementbyId.innerHTML="TRUE";
}
else
{
document.getElementbyId.innerHTML="False";
}

}
</script><br>
</head>
<img id="test" src=""  alt="..." length="75px" width="75px" />

<body>

<input type="button" value="start" onclick="startf()">
<input id="answer" type="text" name="checkvalue" value="Enter Value" onclick="check()">
<div id="fa">
</div>
<input type="button" value=chek onclick="check()">


</body>

3 个答案:

答案 0 :(得分:4)

1-放置并结束每条指令 - &gt; ;

2-不要直接使用document.getElementById,至少会出现一个错误,并且你不希望这样。

function _e(id) {
   return document.getElementById(id);
}

3-始终在IF-ELSE块周围放置括号和(...):

if (...) {
    //....
} else {
    //....
}

4-每个标签属性的值都应为“”,例如:

<input type="button" value="start" onclick="check()" />

5-您只能将图像路径放在数组中,因为它似乎需要在#test图像中更新。

答案 1 :(得分:1)

document.getElementById检查外壳。您的检查功能错误...您无法为document.getElementById函数赋值。你的if也错了。你知道任何JavaScript吗?

答案 2 :(得分:0)

我猜你想要的东西可能是这样的。您似乎只是尝试使用document.getElementById(id) = something添加或替换元素,但这不是它的工作原理。相反,要将图像更改为其他文件,您需要更改其src属性。 (还有其他方法,但这可能是最简单的。)

// Declare the variable called number here so it can be accessed
// by all of the following functions.
var number;

// a simple function to save typing document.getElementById all the time
function _e(id) {
    return document.getElementById(id);
}
function startf() {
    // Pick a number between 1 and 4
    number = Math.floor(Math.random() * 4 + 1);

    // Set the image with id 'test' to have the source 1.png, 2.png etc.
    _e('test').src = number + '.png';
}

function check() {
    // note that == is used for comparison, = is used for assignment
    if (_e('answer').value == number) {
        _e('fa').innerHTML = "TRUE";
    }
    else {
        _e('fa').innerHTML = "False";
    }
}​
相关问题