Javascript 使用jQuery,如何检查表格单元格是否为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1945844/
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-22 22:00:42  来源:igfitidea点击:

Using jQuery, how to check whether a table cell is empty or not?

javascriptjqueryasp.net-ajax

提问by Yaswanth

Using jQuery, how to check whether a table cell is empty or not?

使用jQuery,如何检查表格单元格是否为空?

Please help me.

请帮我。

回答by jitter

What do you mean by empty.

空是什么意思。

//cell maycontain new lines,spaces,&npsp;,... but no real text or other element
$("cellselector").text().trim()=="";

or

或者

//cell has no child elements at all not even text e.g. <td></td>
$("cellselector:empty")

回答by T.J. Crowder

You can use CSS selectors with the $function to get a reference to the cell's element, and then use the htmlfunction to see whether it has any contents. For instance, if the cell has an ID "foo":

您可以使用带有该$函数的CSS 选择器来获取对单元格元素的引用,然后使用该html函数查看它是否有任何内容。例如,如果单元格的 ID 为“foo”:

if ($("#foo").html()) {
    // The cell has stuff in it
}
else {
    // The cell is empty
}

回答by Sarfraz

Try this:

尝试这个:

$content = $('#your_cell_id_here').html();

if($content == '')
{
  // yes it is empty
}
else
{
  // no it is not empty
}

回答by miku

You could add css classes to your tableand its rows and columns, then use jquery selectorsto get the table item:

您可以将 css 类添加到您table的行和列,然后使用jquery 选择器获取表项:

if ( !($('#mytable tr.row-i td.column-j').html()) ) { alert("empty"); }

回答by Keith Rull

You can use the trechnique I posted here

你可以使用我在这里发布的 trechnique

http://www.keithrull.com/2010/06/09/HowToChangeTableCellColorDependingOnItsValueUsingJQuery.aspx

http://www.keithrull.com/2010/06/09/HowToChangeTableCellColorDependingOnItsValueUsingJQuery.aspx

You can use this if you already know the id of the cell you want to check

如果您已经知道要检查的单元格的 ID,则可以使用它

$valueOfCell = $('#yourcellid').html();

or you can iterate on the cells of the table

或者您可以迭代表格的单元格

$("#yourtablename tr:not(:first)").each(function() {                           
//get the value of the table cell located            
//in the third column of the current row             
var valueOfCell = $(this).find("td:nth-child(3)").html();                          
//check if its greater than zero             
if (valueOfCell == ''){                 
    //place action here
}             
else{                 
    //place action here
}         

});

});