简体   繁体   中英

Why can I log and alert value returned from jQuery.width() but can't use in assignment?

I'm simply trying to total the widths of elements before a certain element index and assign that to a variable. I get NaN when using $(this).width() or $(object).width. Yet I can log and alert these numeric values fine?

Mark-up

    <div class="gallery">
        <div class="gallery-imgs" style="color: #000;">
            <div class="gallery-img-slide">
                <img src="http://placehold.it/700x1080">
            </div><div class="gallery-img-slide">
                <img src="http://placehold.it/900x1080">
            </div>
        </div>
    </div>
<script type="text/javascript">
function focusSlide(slide_index) {
debugger;

var offset_width;

if (slide_index === 0) {
    $(".gallery-imgs").css("margin-left",
        ($(".gallery").width() / 2) - $(".gallery-imgs").children().eq(slide_index).width() / 2 + "px");
}
else {
    $(".gallery-imgs").children().each(function(index, object){
        debugger;
        if (index < slide_index) {
            offset_width += $(object).width();
            console.log($(object).width());
        }
    });
}

}

It's because you have var offset_width; .

You need to initialize it to a number like this: var offset_width = 0;

offset_width += 1 really means offset_width = offset_width + 1 .

If you do not set it to anything, that is an invalid statement because you are adding NaN + 1 . Your error is not actually because of $(object).width()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM