得到“;undefined不是函数“;错误

getting "undefined is not a function" error

本文关键字:函数 错误 undefined 得到      更新时间:2023-09-26

我已经研究了几个与此相关的问题,寻找答案,但没有找到答案。下面是产生错误的代码:

function centerGalImages() {
    var len = $('.image').filter(':visible').length;
    for (var i = 0; i < len; i++ {
        var contWidth = $('.img-container')[i].width();
        var imgWidth = $('.image')[i].width();
        var leftOffset = (contWidth/2) - (imgWidth/2);
        img.css({left: leftOffset});
    }
}

我在调用width()时出错。我是JS/JQuery的新手,但对我来说,这看起来应该可以工作。css文件在jquery文件之前加载到html文件中,这里是与.image.img-container相关的css:

.image {
   width: auto;
   height: 100%;
   position: relative;
}
.img-container {
   display: inline-block;
   width: 24.5%;
   height: 200px;
   overflow: hidden;
}

非常感谢任何关于呼叫width()不起作用的想法

编辑:根据要求,这里是相关的HTML:

<div>
    <div class="img-container"><img class="image clickable" src=""/></div>
    <div class="img-container"><img class="image clickable" src=""/></div>
    ...container/image elements are copied 16 times...
</div>

CCD_ 8值被设置在jquery文件的开头。所以当centerGalImages()被调用时,src的值已经被设置为

使用此代码

$('.img-container')[i].width();

您正在尝试调用HTMLImageElementwidth方法。这是不存在的。因此出现了错误。width是jQuery实例的方法,所以应该是

$('.img-container').eq(i).width();

UPD根据HTML结构,这可能看起来更好:

$('.image').filter(':visible').css('left', function() {
    var contWidth = $(this).parent().width();
    var imgWidth = $(this).width();
    return (contWidth/2) - (imgWidth/2);
});