[英]“Uncaught TypeError: Cannot read property 'Name' of undefined” when triggered a function
编辑:我发现该代码工作正常,没有任何错误。 是我自己被模糊了。 对不起,我很抱歉。
我有一个HTML文件,其格式为包含ID为#StuIDtxt的文本框。
也有一些JavaScript,这是我文件中的代码。 提交表单时将触发功能getResult()。
function getResult(){
var StuID = document.getElementById('StuIDtxt').value;
document.getElementById('name').innerHTML = result[StuID].Name;
return false;
}
还有一个变量名“结果”存储从JSON解析的数组。
当我在文本框中填写“ 10001”并提交表单时,JavaScript控制台说
Uncaught TypeError: Cannot read property 'Name' of undefined
但是打字
document.getElementById('name').innerHTML = result['10001'].Name;
在控制台中导致按预期成功执行。
我在功能上做错了吗?
此处的实时网络: https : //srakrn.com/satitnpru/announce
从https://srakrn.com/satitnpru/announce/result_demo.json
检索到的JSON不包含任何ID 10001
。 如果我尝试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
不存在,将导致运行时错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.