2013-07-31 58 views
0

我一直sctatching我的頭,這一個屬性「的innerHTML」,我通常是一個jQuery的傢伙,但我有一個使用原型Magento的擴展,我有點失去了對如何解決這一問題錯誤:遺漏的類型錯誤:無法讀取的不確定

我得到的錯誤:Uncaught TypeError: Cannot read property 'innerHTML' of undefined我猜測,因爲我需要檢查頁面中存在的某些HTML(JavaScript文件出現在每個頁面上,因此可能每次都沒有相關的HTML。

本來我是得到一個spConfig undefined這就是爲什麼我把在if ((typeof spConfig == 'undefined') || !spConfig) {

原始代碼是:

document.observe("dom:loaded", function() { 
if(spConfig.config.dynamics == 1 && spConfig.config.showbottom == 1){ 
    $$('.product-options-bottom')[0].insert({top: new Element('p', {id:'bottom-avail', class:'availability'}).update($$('p.availability')[0].innerHTML)}); 
    if(spConfig.config.showship == 1){ 
     $('bottom-avail').insert({after: new Element('p', {id:'bottom-shipsin', class:'shipsin'}).update($$('p.shipsin')[0].innerHTML)}); } 
} 
}); 

我試圖改變到

document.observe("dom:loaded", function() { 
if ((typeof spConfig == 'undefined') || !spConfig) { 

} else { 
    if(spConfig.config.dynamics == 1 && spConfig.config.showbottom == 1){ 
     if($$('p.availability') != 'undefined'){ 
      $$('.product-options-bottom')[0].insert({top: new Element('p', {id:'bottom-avail', class:'availability'}).update($$('p.availability')[0].innerHTML)}); 
     } 
     if(spConfig.config.showship == 1){ 
      if($$('p.shipsin') != 'undefined'){ 
       $('bottom-avail').insert({after: new Element('p', {id:'bottom-shipsin', class:'shipsin'}).update($$('p.shipsin')[0].innerHTML)}); 
      } 
     } 
} 
} 
}); 

但是我仍然得到錯誤Uncaught TypeError: Cannot read property 'innerHTML' of undefined在線指向$$('.product-options-bottom')[0].insert({top: new Element('p', {id:'bottom-avail', class:'availability'}).update($$('p.availability')[0].innerHTML)});

回答

1

由於$$()方法返回一個列表(或陣列)的CSS選擇器匹配的元素,你不能檢查其undefined - 但你可以檢查列表中返回的元素的數量。

所以試試這個

if($$('p.availability').length != 0) 
{ 
    $$('.product-options-bottom')[0].insert(
     { 
      top: new Element('p', {id:'bottom-avail', 'class':'availability'}).update(
       $$('p.availability')[0].innerHTML 
      )}); 
} 

另外在new Element()class屬性應該是在一個字符串,如類是在某些瀏覽器的關鍵詞,也將在ECMA 6

成爲核心JavaScript語言的一部分
+0

感謝您的班級提示,解決了我在進行長度檢查時遇到的下一個錯誤! –

相關問題