簡體   English   中英

觸發功能時出現“未捕獲的TypeError:無法讀取未定義的屬性'名稱'”

[英]“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不存在,將導致運行時錯誤。

也許是因為“ 10001”不存在

這是來自result var的日志

http://prntscr.com/9mdsjv

我用了“ 00020”,還可以

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM