【问题标题】:How to get width of each dom element in array?如何获取数组中每个dom元素的宽度?
【发布时间】:2015-03-06 08:46:18
【问题描述】:
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);
}
如何获取每个元素的宽度?
【问题讨论】:
标签:
javascript
jquery
arrays
for-loop
【解决方案1】:
我认为如果你这样写会更好:
$('.links li').each(function(d) {
console.log("Width: "+$(this).width())
});
【解决方案2】:
jQuery 返回数组中的对象,当你想在循环中使用每个 DOM 元素时,它可以与 JavaScript 函数一起使用,但 width() 不是本机函数,如果你想使用 jQuery 获取 width @987654324 @方法然后创建jquery object就像$(footLink)这样你也可以使用offsetWidth原生方法
$(footLink).width();
或
footLink.offsetWidth;
【解决方案3】:
为 footLink 使用 jQuery 包装器:
var footLinks = $('.links li');
for (var i = 0; i < footLinks.length; i++) {
var footLink = footLinks[i];
var footLinkWidth = $(footLink).width();
console.log('Width: ' + footLinkWidth);
}