gpt4 book ai didi

javascript - 如何将 $.each 循环中的结果相加?

转载 作者:搜寻专家 更新时间:2023-10-31 22:03:07 25 4
gpt4 key购买 nike

您好我正在尝试读取 topmenu 元素中每个项目的宽度并添加项目的宽度并分配给变量。但是当我运行这段代码时,我得到了 NaN 警报这段代码有什么问题:

$(document).ready(function(){
$('.topmenu').each(function(menu){
var btext = $(this).find('.baritem').width();
alert(btext);
var itemswidth = +itemswidth+btext;
alert(itemswidth);
//var width = getTextWidth(btext,"arial","40");
//alert(width);
});
});

最佳答案

这一行

var itemswidth = +itemswidth+btext;

undefined 添加到一个数字。这给出 NaN。在进入循环之前,您需要将 itemswidth 初始化为 0 :

$(document).ready(function(){
var itemswidth = 0;
$('.topmenu').each(function(){
var btext = $(this).find('.baritem').width();
itemswidth += btext;
console.log(itemswidth); // better than alert
});
});

对于弗洛里安:

$(document).ready(function(){
var itemswidth = $('.topmenu .baritem').get().reduce(function(t,e){
return t+$(e).width()
}, 0);
console.log(itemswidth);
});

关于javascript - 如何将 $.each 循环中的结果相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16707720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com