如果div没有内容隐藏其他div

时间:2012-04-23 16:41:37

标签: javascript jquery html

我有以下JS:

if ( $("#secretContent").children().length == 0) {
    $("#seemore").hide();
}​

这是一个jsFiddle来证明我的问题。当id为“secretContent”的div没有子/内容时,我有意隐藏id为“seemore”的div。

非常感谢任何帮助。提前谢谢!

5 个答案:

答案 0 :(得分:4)

所以......我想用> 0代替== 0

答案 1 :(得分:4)

可能想要将“大于”改为平等:

if ( $("#secretContent").children().length == 0) {
    $("#seemore").hide();
}​

正如Vega建议的那样,如果您关心文本节点,而不是严格的儿童HTML元素,那么您需要使用contents()代替children

if ( $("#secretContent").contents().length == 0) {
    $("#seemore").hide();
}​

以下是演示两者的演示:

http://jsfiddle.net/jtbowden/NASQn/

注意!请注意,.contents()计算div内的任何文字。

此:

<div>
</div>

和此:

<div> </div>

两者都被认为是非空,因为第一个有换行符,第二个有空格,两者都被认为是文本节点。使用.contents()时唯一被认为是空的是:

<div></div>

如果您想对此进行说明,则需要检查否children(),然后查看剩余文本是否仅为空格:

if ( $("#secretContent").children().length == 0) {
    if( $("#secretContent").text().match(/^\s*$/) ) {
        $("#seemore").hide();
    }
}

演示:http://jsfiddle.net/jtbowden/4xtME/

答案 2 :(得分:1)

如果您想检查文字内容,我认为您应该使用.contents代替.children。同时将>更改为==。试着让我知道,

if ( $("#secretContent").contents().length == 0) {
    $("#seemore").hide();
}​

答案 3 :(得分:1)

将“&gt; 0”替换为“== 0”

这应该可以做到!

答案 4 :(得分:1)

这就是诀窍http://jsfiddle.net/chepe263/9Jmug/1/

if ( $("#secretContent").children().length < 1) {
    $("#seemore").hide();
}​

在小提琴中显示内容,因为它在secretContent中有一个aditional div

相关问题