我想创建两个八进制数字,使用jQuery在加法和减法中执行计算但是如果我尝试计算它只会合并的两个值,我是否需要转换parseInt var numberone和number?
$(document).ready(function() {
$("#submit").click(function() {
var numberone = $("#numberone").val();
var operate = $("#operator").val();
var numbertwo = $("#numbertwo").val();
var answer;
switch (operate) {
case "addition":
answer = numberone.toString(8) + numbertwo.toString(8);
break;
case "subtraction":
answer = numberone.toString(8) - numbertwo.toString(8);
break;
case "multiplication":
answer = numberone.toString(8) * numbertwo.toString(8);
break;
case "division":
answer = numberone.toString(8) / numbertwo.toString(8);
break;
case "module":
answer = numberone.toString(8) % numbertwo.toString(8);
break;
default:
answer = "Error Try Again";
}
$("#answer").html("<h1>" + answer + "</h1>");
});
});
&#13;
<form>
<input id="numberone" type="number" name="" required="">
<br>
<select style="" id="operator">
<option value="addition">+</option>
<option value="subtraction">-</option>
<option value="multiplication">*</option>
<option value="division">/</option>
<option value="module">%</option>
</select>
<br>
<input type="number" name="" id="numbertwo" required="">
<br>
<input type="submit" value="Submit" id="submit">
</form>
<br>
<span class="" id="answer"></span>
&#13;
答案 0 :(得分:0)
用parseInt(value,8)替换value.toString(8)以获得该数字的基数为8的版本:
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var numberone = $("#numberone").val();
var operate = $("#operator").val();
var numbertwo = $("#numbertwo").val();
var answer;
switch (operate) {
case "addition":
answer = (parseInt(numberone, 8) + parseInt(numbertwo, 8)).toString(8);
break;
case "subtraction":
answer = (parseInt(numberone, 8) - parseInt(numbertwo, 8)).toString(8);
break;
case "multiplication":
answer = (parseInt(numberone, 8) * parseInt(numbertwo, 8)).toString(8);
break;
case "division":
answer = (parseInt(numberone, 8) / parseInt(numbertwo, 8)).toString(8);
break;
case "module":
answer = (parseInt(numberone, 8) % parseInt(numbertwo, 8)).toString(8);
break;
default:
answer = "Error Try Again";
}
$("#answer").html("<h1>" + answer + "</h1>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="numberone" type="number" name="" required="">
<br>
<select style="" id="operator">
<option value="addition">+</option>
<option value="subtraction">-</option>
<option value="multiplication">*</option>
<option value="division">/</option>
<option value="module">%</option>
</select>
<br>
<input type="number" name="" id="numbertwo" required="">
<br>
<input type="submit" value="Submit" id="submit">
</form>
<br>
<span class="" id="answer"></span>
但是,代码中仍然存在错误,因此可以输出NaN等。