我无法弄清楚为什么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>
我认为这是一个简单的解决方案,它让我疯狂。
答案 0 :(得分:2)
如果你想运行“else”代码以及“if”代码,请删除else语句:
var hotCheck = function(submitVal){
if(i===1){
console.log("try again");
scopedVal = submitVal;
console.log("scopedVal is " + scopedVal);
};
if(Math.abs(scopedVal-checkNum)> Math.abs(submitVal - checkNum)){
console.log("Hotter");
scopedVal = submitVal;
} else {
console.log("colder");
scopedVal = submitVal;
};
};
演示: http://jsfiddle.net/hHC88/
你还需要改变腹肌。到Math.abs
答案 1 :(得分:1)
abs()方法不存在。你正在处理所有整数,所以你可以删除它或完全引用它Math.abs()
答案 2 :(得分:1)
你必须更换
if( abs(scopedVal-checkNum)> abs(submitVal - checkNum)){
到
if( Math.abs(scopedVal-checkNum) > Math.abs(submitVal - checkNum)){
abs()是Math的一种方法。
尝试this