【问题标题】:Using jQuery, how to check whether a table cell is empty or not?使用jQuery,如何检查表格单元格是否为空?
【发布时间】:2010-12-29 02:03:32
【问题描述】:

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

请帮帮我。

【问题讨论】:

标签: javascript jquery asp.net-ajax


【解决方案1】:

你说的空是什么意思。

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 谢谢。但所有这些仅在 IE 中有效,在 Firefox 中无效。我现在检查了。
    • 在 IE7、FF3.5、Chrome3、Safari4 和 Opera10 中测试并运行。测试页面:pastie.org/753004 预期输出:“foo has contents / bar is empty” 一定要允许空格;你可能想修剪html返回的字符串。
    【解决方案3】:

    试试这个:

    $content = $('#your_cell_id_here').html();
    
    if($content == '')
    {
      // yes it is empty
    }
    else
    {
      // no it is not empty
    }
    

    【讨论】:

      【解决方案4】:

      您可以将 css 类添加到您的 table 及其行和列,然后使用 jquery selectors 获取表格项:

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

      【讨论】:

        【解决方案5】:

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

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

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

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

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

        $("#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
        }         
        

        });

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-30
          • 2020-07-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多