TypeError:无法读取未定义的属性“top”

时间:2014-11-04 15:58:01

标签: javascript jquery html css

我一直收到此错误:'未捕获的TypeError:无法读取属性' top'未定义的'。有谁知道我做错了什么?我有两个相同的循环具有不同的值但它们不会执行,第一个循环执行但其余的不执行。我是jQuery的新手,所以如果有人能告诉我我做错了什么,那就太棒了。

for(i=4, x=1; x<16; i=i+3, x=x+3)
{
    var top     = $('.box-' + x).position().top + $('.box-' + x).height() + 10;
    var left    = $('.box-' + x).position().left;

    $('.box-' + i).css({
        top: top,
        left: left
    });
}

我一直收到此错误:&#39;未捕获的TypeError:无法读取属性&#39; top&#39;未定义&#39;。

1 个答案:

答案 0 :(得分:0)

正如@dfsq所指出的,页面上可能无法使用某些目标元素。因此,以下代码仅适用于以下代码:

for(i=4, x=1; x<16; i=i+3, x=x+3)
{
    if( $('.box-' + x).length ) {
        var top     = $('.box-' + x).position().top + $('.box-' + x).height() + 10;
        var left    = $('.box-' + x).position().left;

        $('.box-' + i).css({
            top: top,
            left: left
        });
    }
}
相关问题