我正在制作一个小网站作为测试。对于JavaScript和HTML表单来说是非常新的,所以我想我会把自己投入到我认为是深层次的东西中并且给它一个去。
我试图在页面上显示一个整数,这是一些计算的结果。
我想找到第一个数字(当前值)和第二个数字(期望值)之间的差异,然后将该数字除以25并将其存储为变量。然后我想在消息中显示该变量。
我目前的HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<form>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<input type="submit" onclick="calculate()">
</form>
<script src="js/main.js"></script>
</body>
</html>
我目前的JavaScript:
function calculate() {
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
var difference = desiredRating - currentRating;
var gamesToPlay = difference / 25;
document.write("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
答案 0 :(得分:2)
你在那里是99%。你所要做的就是改变
var currentRating = document.getElementById("currentRating");
var desiredRating = document.getElementById("desiredRating");
进入
var currentRating = parseInt(document.getElementById("currentRating").value);
var desiredRating = parseInt(document.getElementById("desiredRating").value);
你拥有它的方式,这些变量本身只包含HTML(技术上,DOM)元素,而不是它们中的值。这将获取值,然后将它们转换为整数,以便您可以使用它们进行数学运算。如果您这样做,您的网站就会完全按照您的意愿行事。
答案 1 :(得分:1)
小心:
try{
var currentRatingInt = parseInt(currentRating);
}catch(e){
alert(currentRating + " is not an integer");
}
是一个字符串(文本)值...以确保你可以做的int值
document.getElementById("idOfYourDiv").innerHTML = "What you like to display in div";
如果您想在页面中显示结果,可以使用带有和ID的DIV并执行:
{{1}}
答案 2 :(得分:0)
希望此代码有所帮助:
html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
<title>MMR calculator</title>
</head>
<body>
<h1>Type in your current MMR, and your desired MMR and click "Calculate"</h1>
<div>
<input type="text" id="currentRating" placeholder="What is your current MMR?">
<input type="text" id="desiredRating" placeholder="What is your desired MMR?">
<button onclick="calculate();">Calculate</button>
</div>
<script src="js/main.js"></script>
</body>
</html>
javascript:
function calculate() {
var currentRating = document.getElementById("currentRating").value;
var desiredRating = document.getElementById("desiredRating").value;
var gamesToPlay = (desiredRating - currentRating) / 25;
gamesToPlay = Math.abs( parseInt(gamesToPlay) );
alert("You need to play " + gamesToPlay + " to get to " + desiredRating);
}
答案 3 :(得分:-1)
从另一个中减去第一个字段,如果该值不大于0则乘以-1
。
除以25。