javascript - 为什么我可以记录和警报从 jQuery.width() 返回的值,但不能在赋值中使用?

标签 javascript jquery

我只是尝试计算某个元素索引之前元素的宽度总和并将其分配给一个变量。使用 $(this).width() 或 $(object).width 时得到 NaN。但我可以很好地记录和警告这些数值吗?

加价

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

}

最佳答案

这是因为你有var offset_width;

您需要将其初始化为如下数字:var offset_width = 0;

offset_width += 1 真正的意思是 offset_width = offset_width + 1

如果您未将其设置为任何值,则该语句无效,因为您要添加 NaN + 1。您的错误实际上并不是因为 $(object).width()

关于javascript - 为什么我可以记录和警报从 jQuery.width() 返回的值,但不能在赋值中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48858825/

相关文章:

javascript - POST 动态创建的必填输入字段

jquery - css3 旋转动画——开始旋转,然后停在帧上

c# - 从用户控件中的代码隐藏 C# 调用 JavaScript 函数

javascript - 是否可以在没有 flash 的情况下在 IE 中使用 ajax 上传进度条?

javascript - 如何在Appcelerator/titanium Android中创建无间隔的Android服务?

javascript - 动态添加 Controller 到 ng-include

php - 如果使用 jquery 出现错误,则无法为某些字段显示红色

javascript - 将多个视频返回到海报照片

javascript - WEB AUDIO API 产生雨噼啪声

javascript - jQuery 单击该类将被添加到随机列表项中