2013-07-31 61 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

感谢您的班级提示,解决了我在进行长度检查时遇到的下一个错误! –

相关问题