"未捕获的类型错误:无法读取属性'名称'未定义的“;当触发一个功能时

"Uncaught TypeError: Cannot read property 'Name' of undefined" when triggered a function

本文关键字:功能 一个 未定义 属性 quot 类型 错误 读取 名称      更新时间:2023-09-26

EDIT:我发现代码运行良好,没有任何问题。模糊的是我自己。很抱歉没有谨慎

我有一个HTML文件,其中包含一个ID为#StuIDtxt的文本框。

还有一些JavaScript,这里是我的文件中的一段代码。函数getResult()将在表单提交时触发。

function getResult(){
  var StuID = document.getElementById('StuIDtxt').value;
  document.getElementById('name').innerHTML = result[StuID].Name;
  return false;
}

还有一个变量名"result"存储从JSON解析的数组。

当我在文本框中填写"10001"并提交表格时,JavaScript控制台显示

Uncaught TypeError: Cannot read property 'Name' of undefined

但是键入

document.getElementById('name').innerHTML = result['10001'].Name;

在控制台中,结果按预期成功执行。

我在函数中做错了什么吗?

此处为Live web:https://srakrn.com/satitnpru/announce

https://srakrn.com/satitnpru/announce/result_demo.json检索到的JSON不包含10001的任何id。如果我尝试00001,则不会出现错误。更改如下:

function getResult(){
  var StuID = document.getElementById('StuIDtxt').value;
  if ( StuID != null && StuID.trim() != "" )
  {
       if ( typeof result[StuID] != "undefined" )
           document.getElementById('name').innerHTML = result[StuID].Name;
       else
           alert("Unknonw ID: " + StuID);
  }
  return false;
}

在您的代码中,您假设给定的ID将始终存在于result中,并直接引用Name。如果StuID不存在,这将导致运行时错误。

也许是因为"10001"不存在

这是来自result var 的日志

http://prntscr.com/9mdsjv

我使用了"00020"及其OK