【问题标题】:.width() giving error $(...)[0].width is not a function?.width() 给出错误 $(...)[0].width 不是函数?
【发布时间】:2016-01-04 15:03:22
【问题描述】:

我有一张桌子,我正在尝试找出表格中每个 td 的宽度。我尝试了各种变体:$("td")[0].width(),但都没有工作,每次都得到错误:"Uncaught TypeError: $(...)[0].width is not a function"

我首先导入 jQuery,在我的其他 JS 文件 (https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js) 之前,我使用的是 .width() 而不是 .width。

有什么想法吗?

【问题讨论】:

  • [0] 获取 DOM 元素 - 而 DOM 元素没有 .width() 方法。如果你想要第一个元素,请使用.first() - $("td").first().width()
  • 请发布一个完整的代码示例。

标签: jquery


【解决方案1】:

$("td")[0] 是 DOM 元素而不是 jquery 对象。只需将其包装为 jquery $($("td")[0]).width()

您需要获取每个 td 的宽度,以便您可以使用类似

$.each('td', function() {
    var currentTDWidth = $(this).width(); // more code here
});

【讨论】:

  • 为什么要针对 td 添加#
  • 我的错。我写的很匆忙,没有看。已编辑
  • 其他答案也很有帮助,这个有效。非常感谢:D
【解决方案2】:

使用 eq(0) 而不是 [0] 来保留具有 width() 函数的 jQuery 对象。

【讨论】:

    【解决方案3】:

    当你说我试图找到表格中每个 td 的宽度所以你需要使用 .each() 循环遍历 tds ..

    $('td').each(function(){
       alert($(this).width());
    });
    

    选择特定的 td 还有更多方法

    通过使用:eq() 选择器

    $('td:eq(0)');   // index start from 0
    

    或者.eq()在jquery中

    $('td').eq(0)        // index start from 0
    

    :nth-child()选择器

    $('td:nth-child(1)');    // index start from 1
    

    【讨论】:

      【解决方案4】:
      $("td")[0]
      

      是一个 DOM 级别元素,而不是一个 jQuery 对象。 .width() 是一个 jQuery 方法,所以你不能在上面使用它。 执行以下任一操作:

      $("td").eq(0).width(); // On a jQuery object
      $("td")[0].offsetWidth; // On a DOM Level Element.
      

      要获取所有元素的宽度,请使用.each

      $('td').each(function(){
         alert($(this).width());
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多