我正在从HTML读取一个值,对该值加1,然后更新HTML中的数字。当我这样做时,它会将数字作为NaN
返回到HTML。
我尝试使用parseInt()
和Number()
,但仍然得到相同的输出。
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="style.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div class="inputForm">
<form id="frm1" onsubmit="return formSubmit()">
<h3>Update League Table!</h3>
<section class="playerOne">
<label for="playerOne">Player One Name:</label>
<select name="playerOne" id="playerOne">
<option value="name1">name1</option>
<option value="name2">name2</option>
<option value="name3">name3</option>
<option value="name4">name4</option>
</select>
</section>
<br>
<section class="playerTwo">
<label class="playerTwoText" for="playerTwo">Player Two Name:</label>
<select name="playerTwo" id="playerTwo">
<option value="name1">name1</option>
<option value="name2">name2</option>
<option value="name3">name3</option>
<option value="name4">name4</option>
</select>
<br>
</section>
<br>
<section class="winner">
<span>Please select winner:</span>
<br>
<input id="userOne" type="radio" name="winnerWinner" value="userOne">
<label for="userOne">Player One</label>
<input id="userTwo" type="radio" name="winnerWinner" value="userTwo">
<label for="userTwo">Player Two</label>
</section>
<br>
<section class="submission">
<input type="submit" value="Submit">
</section>
<p id="submitComplete">testing</p>
<p id="name1GP">0</p><p id="name1Wins">0</p>
</form>
</div>
</body>
</html>
JAVASCRIPT
function formSubmit() {
var p1 = document.getElementById("playerOne").value;
var p2 = document.getElementById("playerTwo").value;
var radiobox = document.querySelector('input[name="winnerWinner"]:checked').value;
if (p1 === "name1" && radiobox === "userOne") {
var name1GP = document.getElementById("name1GP").value;
name1GP += 1
document.getElementById("name1GP").innerHTML = name1GP
}
return false;
}
我正在读取的值为id="name1GP"
,我想向此值添加1
,然后将其返回到HTML,但是与其返回1
,它返回的是NaN
答案 0 :(得分:1)
段落元素没有.value。您需要获取innerHTML作为int。
if (p1 === "name1" && radiobox === "userOne") {
var name1GP = parseInt(document.getElementById("name1GP").innerHTML);
name1GP += 1
document.getElementById("name1GP").innerHTML = name1GP
}
答案 1 :(得分:1)
p标签不应具有任何value属性,您应该使用var name1GP = parseInt(document.getElementById("name1GP").innerHTML, 10);
var val = document.getElementById('test').value;
console.log(val);
var val2 = document.getElementById('test').innerHTML;
console.log(val2, typeof val2);
var val3 = parseInt(document.getElementById('test').innerHTML, 10);
console.log(val3, typeof val3);
<p id="test">0</p>
答案 2 :(得分:0)
尝试这个。
var name1GP = document.getElementById("name1GP").innerHtml;
name1GP = parseInt(name1GP) + 1
document.getElementById("name1GP").innerHTML = name1GP
答案 3 :(得分:-1)
HTML中的值呈现为字符串。
字符串+数字将得到NaN
。
更改代码以将字符串解析为数字:
name1GP = parseInt(document.getElementById("name1GP").value)
这应该可以解决问题。