【问题标题】:Set the width of table headings TH with jQuery使用 jQuery 设置表格标题 TH 的宽度
【发布时间】:2012-07-05 17:23:20
【问题描述】:

我正在使用带有自定义行模板的 Telerik mvc 网格。因此,由于我已经完成了行模板,因此我的宽度有问题。我无法正确设置宽度,所以我无法制作一个简单的文档就绪函数来设置每个 th 的宽度。

function SetWidth(){
    var ths = $('th');
    var element = ths[0];
    element.width(100);
}

然后我手动设置 0 = 100, 1 = 110, 2 = 300 px 等等。

但是当我尝试添加 'element' 的宽度时,它给了我错误。

Uncaught TypeError: Property 'width' of object #<HTMLTableCellElement> is not a function

有什么问题?

【问题讨论】:

    标签: jquery jquery-selectors telerik


    【解决方案1】:

    因为您使用的是标准 DOM 元素。你可以像这样改变宽度

    function SetWidth(){
        var ths = $('th');
        var element = ths[0];
        element.style.width = 100;
    }
    

    var ths = $('th');
    var element = ths.eq(0); //<-- instead of ths[0]
    element.width(100);
    

    【讨论】:

      【解决方案2】:

      width() 不是标准 DOM 元素的有效 javascript 方法,这是您在使用 $("th")[0] 时传递的元素类型。虽然它是 jQuery 的一种方法。

      你会想要这样做:

      function SetWidth(){
          var widths = [100, 110, 300]
          for(var i=0; i<widths.length; i++){
              $('th')[i].style.width = widths[i];
          }
      }
      

      【讨论】:

      • 这个工作,但我想给我的 TH`s 不同的宽度。例如 Name - 200px Name2 - 100px
      • 让我知道这是否有效。我不确定你在问什么?你想为每个 th 设置一个手动值吗?还是希望每一个都比上一个少 100?
      • 即使您想使用另一个作为您的解决方案,请务必查看此解决方案。与当前解决方案相比,它将使用更少的代码和更快的编辑速度。
      【解决方案3】:

      尝试使用 css 方法:

      element.css('width', '100');
      

      【讨论】:

        【解决方案4】:

        您将 jQuery 元素重新转换为标准 DOM 元素,而标准 DOM 元素上没有 width 方法。

        【讨论】:

          【解决方案5】:

          试试这个:

          function SetWidth(){
              var ths = $('th');
              var element = ths[0]; // this gets a raw dom object
              element.style.width = 100; // therefor you should use style property
          }
          

          或者,如果您想选择第一个 th 元素,您可以使用 jQuery eq() 方法:

              var ths = $('th:eq(0)').css('width', '100')
          

          【讨论】:

            猜你喜欢
            • 2012-09-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-03-26
            • 1970-01-01
            • 2014-07-09
            • 1970-01-01
            • 2019-01-06
            相关资源
            最近更新 更多