【问题标题】: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);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-29
        • 1970-01-01
        • 2011-12-28
        • 2023-03-26
        • 1970-01-01
        • 2016-04-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多