[英]Using Comparison Operators correctly
I am new to HTML and have used Eclipse for Java before. 我是HTML新手,之前曾使用Eclipse for Java。 Below I am trying to have the user input a number (0-5) and have the computer try and guess it.
下面我试图让用户输入一个数字(0-5)并让计算机尝试猜测它。
I have looked this over and it seems sound, the only thing that I have never done is put an item equal to another item at the end of the loop. 我看了这个,看起来似乎是声音,我从未做过的唯一事情就是在循环结束时将一个项目等于另一个项目。
Also first time using not statements ( is it !== or !=?
) in HTML/JavaScript
. 也是第一次在
HTML/JavaScript
使用not语句( is it !== or !=?
)。
HTML HTML
<p>How many fingers am I holding up?</p>
<input id="fingers"></input>
<div>
<button id="button">Input fingers</button>
</div>
JavaScript JavaScript的
var i = 0;
var cg = 0;
document.getElementById("button").onclick = function() {
while (i !== fingers) {
cg = Math.random();
cg = cg * 6;
cg = Math.floor(cg);
if (document.getElementById("cg").value !== fingers) {
alert("Wrong we found " + cg);
i = cg;
} else {
alert("The number of fingers is " + cg);
i = cg;
}
}
}
I am independently learning this for future use, I hope you can help! 我是独立学习这个以备将来使用,希望你能帮忙! Thanks.
谢谢。
You don't have html element with id cg
, so this line fails document.getElementById("cg").value
. 你没有带id
cg
html元素,所以这行没有document.getElementById("cg").value
。 However you have fingers
as an html textbox. 但是你有
fingers
作为html文本框。
Also first time using not statements (is it !== or !=?) in HTML/JavaScript.
也是第一次在HTML / JavaScript中使用not语句(是!==或!=?)。
In js, both are valid but they differ in functionality, !=
has an overhead of conversion. 在js中,两者都有效但功能不同,
!=
具有转换开销。 For eg 例如
5 != '4' // true
5 != '5' // false
5 !== '4' // true
5 !== '5' // true
5 !== 5 // false
5 !== 4 // true
I tried to rectify your code and I ended up with this, hope it helps: 我试图纠正你的代码,我最终得到了这个,希望它有所帮助:
<script type="text/javascript">
var cg;
var fingers = document.getElementById("fingers");
document.getElementById("button").onclick=function() {
cg = Math.floor(Math.random() * 6);
if (fingers.value != cg) {
alert ("Wrong, it was: " + cg);
}
else {
alert ("Right !!");
}
};
</script>
<script type="text/javascript">
var i = 0;
var cg = 0;
document.getElementById("button").onclick = function() {
while (i !== fingers.value) {
cg = Math.random();
cg = cg * 6;
cg = Math.floor(cg);
if (parseInt(cg) !== parseInt(fingers.value)) {
alert("Wrong we found " + cg);
i = cg;
} else {
alert("The number of fingers is " + cg);
break;
}
}
}
</script>
Check your IDs! 检查你的ID! Your JS is trying to find an element that is identified as 'cg', but the only IDs I see are 'button' and 'fingers'.
你的JS试图找到一个标识为'cg'的元素,但我看到的唯一ID是'button'和'fingers'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.