0

我一直在用这个来解决我的问题,我通常是一个 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)});

4

1 回答 1

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
            )});
}

中的class属性也new Element()应该是字符串,因为类在某些浏览器中是关键字,也将成为 ECMA 6 中核心 Javascript 语言的一部分

于 2013-07-31T16:57:43.083 回答