【发布时间】:2014-06-03 01:48:36
【问题描述】:
我无法弄清楚为什么 if/else 语句没有正确执行。该代码仅通过 if(i===1) 循环运行,仅此而已。我正在做一个简单的练习,检查提交的数字,看看用户是否会变得更热或更冷到预设的数字。
<html>
<head>
<title>Test</title>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
var checkNum = Math.floor(Math.random() * 10);
alert("Random number is" + checkNum);
var i = 0;
var scopedVal;
var submitVal;
var hotCheck = function (submitVal) {
if(i === 1) {
alert("try again");
scopedVal = submitVal;
alert("scopedVal is" + scopedVal);
} else {
if(abs(scopedVal - checkNum) > abs(submitVal - checkNum)) {
alert("Hotter");
scopedVal = submitVal;
} else {
alert("colder");
scopedVal = submitVal;
}
}
};
$('.subm').on('click', function () {
i++;
alert(" i is" + i);
alert("button pressed");
submitVal = $(this).closest('#outsideContainer').find('.num').val();
if(submitVal === checkNum) {
alert("You got it");
} else {
hotCheck(submitVal);
}
});
});
</script>
<style>
body {
width: 900px;
color: white;
margin: auto;
}
#outsideContainer {
width: 400px;
color: grey;
margin: auto;
position: relative;
}
</style>
</head>
<body>
<div id="outsideContainer">
<form>
<input type="text" name="text" class="num">
<br/>
</form>
<div id="buttonSubm">
<button class="subm">Submit</button>
<div></div>
</body>
</html>
我假设这是一个简单的解决方法,它让我发疯了。
【问题讨论】:
-
尝试 == 而不是 ===。如果有的话,你在 Firebug(或控制台等)中遇到什么样的错误?
-
您是否尝试在您的
checkNum变量中获取随机数范围?如果是这样,你需要这样做。Math.floor(Math.random() * 7) + 1(给你一个介于 1 和 7 之间的数字)。 -
abs定义在哪里? -
您的 HTML 缺少一对
</div> -
@Geroy290:
===在 JavaScript 中完全可以接受,您可能会将 JS 误认为是其他语言。
标签: javascript jquery loops if-statement