无法读取null的属性“ age”

时间:2018-11-26 15:00:51

标签: javascript

所以我做了这个简单的js代码,它给我一个错误消息“无法读取null的属性'age'。我不明白为什么。有人可以帮助我吗?

    <head>
<script type="text/javascript">
function check(form){
if(form.age.value <=  "18"){
 alert("you can drink")
}
 else{
 alert("You can not drink")

 }
}
  </script>

</head>
<body>

<form>
<input type="text" placeholder="Your age" name="age" id="age">
<input type="button" value="Check" onclick="check(this.form)"

</form>
</body>

<style>
head{
text-align:center;
  color:white;
  background-color:black;
  }
  body{
  text-align:center;
  background-color: brown;
  }

3 个答案:

答案 0 :(得分:1)

您错过了关闭输入标签的时间

更改此:

<input type="button" value="Check" onclick="check(this.form)"

通过这个:

<input type="button" value="Check" onclick="check(this.form)">

答案 1 :(得分:0)

我不会以这种方式访问​​表单的属性。

相反,请使用示例Document.getElementById()

获取输入元素

另外,我认为18岁以下的人不能喝:)

我通过onclick="check()"更改了输入中的函数调用(并且您忘记了关闭标签)

function check(){
  let age = document.getElementById('age');
  if(age.value >=  "18") {
    alert("you can drink")
  }
  else {
    alert("You can not drink")
  }
}
<form>
<input type="text" placeholder="Your age" name="age" id="age">
<input type="button" value="Check" onclick="check()">
</form>

答案 2 :(得分:0)

该错误应该是结果,这很有趣...但是问题是您缺少按钮html上的结束>。如果您修复了该问题,就可以解决该问题:

<script type="text/javascript">
function check(form){
if(form.age.value >  18){
 alert("you can drink")
}
 else{
 alert("You can not drink")

 }
}
  </script>


<form>
<input type="text" placeholder="Your age" name="age" id="age">
<input type="button" value="Check" onclick="check(this.form)">

</form>

<style>
head{
text-align:center;
  color:white;
  background-color:black;
  }
  body{
  text-align:center;
  background-color: brown;
  }
</style>

旁注:读者可见的内容不应放在页面的<head>中(不确定css为何对其进行样式设置),并且您通常不想在结束body标记后放置任何内容。

相关问题