jQuery 获取 td 宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13285362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:28:28  来源:igfitidea点击:

jQuery get td width

jquerywidthhtml-table

提问by aldimeola1122

I want to learn with jQuery "td width", for an example:

我想学习jQuery“td宽度”,例如:

if(td.width=="100"){
    alert("td width = 100");
}

Please explain.

请解释。

<table width="200" border="1">
    <tr>
        <td width="100">Number</td>
        <td width="50">Order</td>
    </tr>
    <tr>
        <td width="100">1</td>
        <td width="50">Car</td>
    </tr>
</table>

回答by Pete Uh

here's a simple extension, the css could be edited to do something less intrusive.

这是一个简单的扩展,可以编辑 css 以减少干扰。

var tdWidthLimit = 100;

$('td').each(function() {
    tdWidth = $(this).width();
    if (tdWidth >= tdWidthLimit)
    {    
        alert('hightlighted td width is ' + tdWidth);
        $(this).css({'background-color' : '#f00'});
    }
});

working demo here?

这里工作演示?

回答by Anton

$('td').each(function(){
      if($(this).width() == 100){
           alert(this.textContent + " width = 100");
      }
});

This will look through all your tds and then alert the td's text content and "width = 100" if the width is 100

这将查看您所有的 tds,然后在宽度为 100 时提醒 td 的文本内容和“width = 100”

回答by voigtan

jQuery width is a method, you need to call the method:

jQuery width 是一个方法,需要调用该方法:

if(td.width() === 100) {
    alert("td width = 100");
}

and td must be a jQuery object of course. Note that it will take the first element in the jQuery object collection and get its width. if you have many elements in that you need to use .each() to loop every element in that collection.

并且 td 当然必须是一个 jQuery 对象。请注意,它将获取 jQuery 对象集合中的第一个元素并获取其宽度。如果你有很多元素,你需要使用 .each() 来循环该集合中的每个元素。

回答by nepjua

here:

这里:

if($('table td').width() == 100) {
    alert('width == ' + $('table td').width());
}

回答by iMoses

I suggest you have a little read at jQuery Fundamentalsif you wish to understand jQuery better.

如果您希望更好地理解 jQuery,我建议您阅读一些jQuery Fundamentals

In your current example it should look something like this:

在您当前的示例中,它应该如下所示:

if($('td').width() === 100) {
    alert("td width = 100");
}

Notice that it will have problems if case you have more than one tdelement in your page, so I suggest you think of a more specific query selector.

请注意,如果td页面中有多个元素,则会出现问题,因此我建议您考虑更具体的查询选择器。