未捕获的类型错误:无法读取属性'innerHTML'的未定义

Uncaught TypeError: Cannot read property 'innerHTML' of undefined

本文关键字:属性 未定义 innerHTML 读取 类型 错误      更新时间:2023-09-26

我一直在思考这个问题,我通常是一个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)});

因为$$()方法返回与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语言的一部分