:tbody标签上的空选择器

时间:2013-07-30 05:44:03

标签: jquery html css jquery-selectors css-selectors

鉴于下表:

<table id="incidents">
    <thead>
        <tr>
            <th></th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

使用jQuery,以下评估为false

$("#incidents tbody").is(":empty")

我想使用CSS将内容设置为消息:

#incidents tbody:empty {
    content: "<tr>message foo</tr>";
}

:empty选择器可以应用于tbody吗?

7 个答案:

答案 0 :(得分:20)

不,遗憾的是tbody中的缩进和换行符阻止它在这种情况下匹配:empty。这适用于CSSjQuery,据我所知:empty行为相同,以及jQuery的:parent,相当于:not(:empty)(用非常选择不好的名字。)

此外,you cannot use CSS content to add elements to the DOM。您需要在jQuery或服务器端执行此操作:检查tbody是否包含任何行,如果没有,请添加该行。

如果你使用jQuery,你可以使用它:

var tbody = $("#incidents tbody");

if (tbody.children().length == 0) {
    tbody.html("<tr>message foo</tr>");
}

答案 1 :(得分:3)

在这种情况下,tbody包含空格作为内容,因此无法正常工作

:empty

  

:empty伪类表示任何没有子节点的元素   所有。只有元素节点和文本(包括空格)   考虑。注释或处理说明不影响是否   一个元素被认为是空的。

此外,:content只能与:before:after伪元素一起使用

  

内容CSS属性与:: before和:: after一起使用   用于在元素中生成内容的伪元素。插入的对象   使用content属性是匿名替换元素。

答案 2 :(得分:2)

如果你想使用:empty,你需要给出如下的tbody语法:

<tbody></tbody>

正如您所定义的那样:empty将不会检查它是否有新行。

按照我的说法定义tbody。 您还可以使用.html()检查条件:

if(!$("#incidents tbody").html()) {}

参考: How do I check if an HTML element is empty using jQuery?

答案 3 :(得分:2)

<tbody>不为空,因为它包含空格。你必须使用过滤功能来解决这个问题:

$("#incidents tbody").filter(function() {
    return !$.trim($(this).text());
}).append('<tr>message foo</tr>');

或计算孩子的数量:

$("#incidents tbody").filter(function() {
    return !$(this).children().length;
}).append('<tr>message foo</tr>');

答案 4 :(得分:1)

仅供参考:您可以使用以下jQuery选择器选择一个空tbody的表,而不依赖于table元素的id:

$("table:not(:has(>tbody>tr))")

答案 5 :(得分:0)

使用

$("#incidents tbody").html()

然后检查你得到了什么。

答案 6 :(得分:-1)

检查:

<table id="incidents">
    <thead>
        <tr>
            <th></th>
        </tr>
    </thead>
    <tbody></tbody>
</table>