getElementById 没有返回任何内容或者脚本中存在问题?
2020-05-17
54
我正在编写一个程序,该程序从输入字段返回值,然后根据条件将字段的字符串更改为 x 结果。非常感谢您的帮助,因为这里的成员过去总是给我很大的帮助。调试器抛出了这个错误,当然什么都不起作用:
script.js:22 Uncaught TypeError: Cannot set property 'innerHTML' of null
at uberChecker (script.js:22)
at HTMLButtonElement.onclick (index.html:25)
这是我的代码(初学者在这里):
JS:
var username = document.getElementById("myUsername").value;
var groupIs = document.getElementById("myGroup").value;
var warnings = document.getElementById("myWarning").value;
var postCount = document.getElementById("myPostCount").value;
function uberChecker() {
if ((groupIs != ('Uber' || 'uber') && postCount > '1000') && warnings === '0') {
document.querySelector("output-box").innerHTML = "You can become Uber !";
} else if (postCount < '1000' && warnings === '0') {
document.querySelector("output-box").innerHTML = (username + ' You have ' + postCount + ' posts, you do not meet the requirements');
} else if (warnings != '0' && postCount > '1000') {
document.querySelector("output-box").innerHTML = (username + ' You cannot upgrade with ' + warnings + ' warning')
} else if (postCount < '1000' && warnings != '0') {
document.querySelector("output-box").innerHTML = (username + ' you have ' + postCount + ' posts which is less than 1000 and you have ' + warnings + '% warning. You cannot upgrade');
} else {
document.querySelector("output-box").innerHTML = (username + ' You are already Uber');
}
}
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="blue-box"></div>
<input type="text" placeholder="Type username" id="myUsername" class="user" >
<input type="text" placeholder="Type user group" id="myGroup" class="group">
<input type="text" placeholder="Type post count" id="myPostCount" class="post">
<input type="text" placeholder="Type warning level" id="myWarning" class="warning">
<div class="UsernameText">Username</div>
<div class="groupText">Group</div>
<div class="postText">Posts</div>
<div class="warningText">Warning</div>
<button type="button" onclick="uberChecker();" class="black-box">Check if you are upgradeable</button>
<div class="output-box">Result will display here</div>
<script src="script.js"></script>
</body>
</html>
3个回答
在类名前加一个点。
document.querySelector(".output-box").innerHTML = "You can become Uber !";
pearllv
2020-05-17
问题出在这行
document.querySelector("output-box").innerHTML
querySelector 函数采用选择器
只需将其更改为
document.querySelector(".output-box").innerHTML
它就可以工作了
Gendy
2020-05-17
问题在于这些语句:
document.querySelector("output-box")
您在这里寻找的是元素而不是类。您需要在类名前面添加一个点 (.),以便 querySelector 正常工作:
document.querySelector(".output-box")
Gh05d
2020-05-17