gpt4 book ai didi

javascript - if/else 语句不起作用

转载 作者:行者123 更新时间:2023-11-28 15:40:18 24 4
gpt4 key购买 nike

我不明白为什么 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>

我假设这是一个简单的修复,但它让我发疯。

最佳答案

如果您想运行“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

关于javascript - if/else 语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24005913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com