JavaScript:需要帮助订购我的JS“未捕获的TypeError:无法读取null的属性'值' [英] JavaScript: Need help ordering my JS "Uncaught TypeError: Cannot read property 'value' of null"

查看:133
本文介绍了JavaScript:需要帮助订购我的JS“未捕获的TypeError:无法读取null的属性'值'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我得到Uncaught TypeError:


无法读取null的属性'value'。

问题在于我的js命令和它调用DOM的顺序,但我不确定究竟在哪里。



有人在帮助我指出正确的方向



以下是我的代码:

 < title>< ; /标题> 
< / head>
< body>
< form>
< input id =todoItemtype =textplaceholder =Todo Item/>
< input type =buttonvalue =Saveonclick =insert(); />
< / form>
< div id =display>< / div>
< script type =text / javascriptsrc =main-2.js>< / script>
< / body>
< / html>

main-2.js:

  var todos = []; 

var todoInput = document.getElementById(todoItem);

var messageBox = document.getElementById(display);

函数insert(){
todos.push(todoInput.value);

clearAndShow();
}

函数clearAndShow(){

todoInput.value =;

messageBox.innerHTML =;

messageBox.innerHTML + =标题:+ todos.join(,)+< br />;
}


解决方案

把此行:

  var todoInput = document.getElementById(todoItem); 

放入函数 insert



当var todoInput是init时,元素不存在。

  function insert() {
var todoInput = document.getElementById(todoItem);
todos.push(todoInput.value);

clearAndShow();
}

清除输入写这段代码

  document.getElementById(todoItem)。value =''; 


I am an amateur JS person so be kind with your voting as I am new to this.

I am getting Uncaught TypeError:

Cannot read property 'value' of null.

I realize the issue is with the order of my js and the order in which it is calling DOM, but I am not sure exactly where.

Someone mind helping point me in the right direction?

Here is my code:

<title></title>
</head>
<body>
  <form>
    <input id="todoItem" type="text" placeholder="Todo Item" />
    <input type="button" value="Save" onclick="insert();" />
  </form>
  <div id="display"></div>
<script type="text/javascript" src="main-2.js"></script>
</body>
</html>

main-2.js:

var todos  = [];

var todoInput  = document.getElementById("todoItem");

var messageBox  = document.getElementById("display");

function insert() {
 todos.push(todoInput.value);

 clearAndShow();
}

function clearAndShow() {

  todoInput.value = "";

  messageBox.innerHTML = "";

  messageBox.innerHTML += "Titles: " + todos.join(", ") + "<br/>";
}

解决方案

put this line:

var todoInput  = document.getElementById("todoItem");

into the function insert

when the var todoInput is init the element not exists.

function insert() {
  var todoInput  = document.getElementById("todoItem");
  todos.push(todoInput.value);

  clearAndShow();
}

to clear input write this code

document.getElementById("todoItem").value='';

这篇关于JavaScript:需要帮助订购我的JS“未捕获的TypeError:无法读取null的属性'值'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆