如何获取数组中每个DOM元素的宽度?

3

footLinks是通过jquery选择的DOM元素数组。下面是我正在处理的代码:

var footLinks = $('.links li');

for (var i = 0; i < footLinks.length; i++) {
    var footLink = footLinks[i];
    var footLinkWidth = footLink.width();
    console.log('Width: ' + footLinkWidth);
}

如何获取每个元素的宽度?


你的代码有什么问题? - Rory McCrossan
3个回答

6

我认为如果你这样写会更好:

$('.links li').each(function(d) {
    console.log("Width: "+$(this).width())
});

1
jQuery返回数组中的对象,当您想要在与JavaScript函数一起循环使用时使用每个DOM元素,但width()不是原生函数,如果您想要使用jQuery width()方法获取宽度,则需要创建jquery对象,例如$(footLink),这样您也可以使用offsetWidth本地方法。
$(footLink).width();

或者

footLink.offsetWidth;

0
使用jQuery包装器来处理footLink:
var footLinks = $('.links li');

for (var i = 0; i < footLinks.length; i++) {
    var footLink = footLinks[i];
    var footLinkWidth = $(footLink).width();
    console.log('Width: ' + footLinkWidth);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接