为什么在使用getElementById时会收到“ TypeError:无法读取null的属性'value'”的信息?

Ary*_*cha -1 javascript function

在下面的代码中:

function Transact() {
    if(document.getElementById('itctobuy').value!='') {
        itctobuy = parseInt(document.getElementById('itctobuy').value);
    }
    if(document.getElementById('steamtobuy').value!='') {
        steamtobuy = parseInt(document.getElementById('steamtobuy').value);
    }
    if(document.getElementById('reltobuy').value!='') {
        reltobuy = parseInt(document.getElementById('reltobuy').value);
    }
    if(document.getElementById('airtobuy').value!='') {
        airtobuy = parseInt(document.getElementById('airtobuy').value);
    }
    if(document.getElementById('bsnltobuy').value!='') {
        bsnltobuy = parseInt(document.getElementById('bsnltobuy').value);
    }
    updateValues();
}
Run Code Online (Sandbox Code Playgroud)

该功能由一个简单onclick的按钮执行。有5个textarea元素,用户可以输入任意数字,如果textarea值不为空,则单击按钮时,值应存储在这些变量中(尽管即使不为空,也不能使用)当下)。
如果我删除了整个块,则updateValues()可以很好地执行,而将其放回原位将导致它无法执行,因此问题就出在这里。这是什么原因,我该如何解决?

编辑:控制台显示以下内容:

未被捕获的TypeError:在HTMLButtonElement.onclick上的TRANSACT无法读取null的属性“值”

那么,此错误的原因是什么?当我输入所有文本字段并且它们的值不为null时,它不起作用。

T.J*_*der 5

Uncaught TypeError: Cannot read property 'value' of null

这告诉您在代码运行时这些元素中至少有一个不存在,因此getElementById返回null,您正尝试从中读取该value属性。

getElementByIdnull当您调用文档时,如果文档中不存在具有给定ID的元素,则只会返回。通常,不存在该元素的原因可归为以下几类:

  1. 打电话getElementById太早
  2. 拼写id错误(例如拼写错误)
  3. 使用name而不是id
  4. 元素存在,但不在文档中 (稀有)

在您的情况下,由于这是单击按钮,因此可能是#2或#3。通过查看错误标识的行,或使用浏览器的调试器逐个语句遍历代码,可以查看不满意的ID。

让我们看一下每个类别:

1.打电话getElementById太早

一个常见的错误是让代码调用getElementById一个script块的之前的HTML,像这样的元素:

<script>
document.getElementById("foo").innerHTML = "bar";
</script>
<!-- ...and later... -->
<div id="foo"></div>
Run Code Online (Sandbox Code Playgroud)

该代码运行时该元素不存在。

解决方案

  • 将移至scriptHTML的末尾,即结束</body.标记之前
  • 将您的呼叫getElementById置于回调中,例如在DOMContentLoaded事件上,或单击按钮等。

不要使用window.onload<body onload="...">除非您真的要等到所有外部资源(包括所有图像)都已加载,然后再运行代码。

2.拼写错误 id

getElementById("ofo")当使用定义元素时,这确实很常见id="foo"

例:

<div id="foo"></div>
<script>
document.getElementById("ofo").innerHTML = "I'm foo"; // Error
</script>
Run Code Online (Sandbox Code Playgroud)

解决方案:使用正确的ID。:-)

3.使用name代替id

getElementById("foo")寻找一个元素与id="foo"name="foo"name!= id

例:

<input name="foo" type="text">
<script>
document.getElementById("foo").value = "I'm foo"; // Error
</script>
Run Code Online (Sandbox Code Playgroud)

解决方案:使用id,不name。:-)(或使用查找元素document.querySelector('[name="foo"]')。)

4.元素存在,但不在文档中

getElementById看起来在文档中的元素。因此,如果该元素已创建,但尚未添加到文档中的任何位置,则将找不到该元素。

例:

var div = document.createElement("div");
div.id = "foo";
console.log(document.getElementById("foo")); // null
Run Code Online (Sandbox Code Playgroud)

它不会在整个内存中查找,而只是在文档中查找(特别是您在其上调用的文档;例如,不同的框架具有不同的文档)。

解决方案:确保元素在文档中;也许您忘了在创建后附加它?(但是在上面的示例中,您已经有了对它的引用,因此完全不需要getElementById。)