我有以下JS:如果div有没有内容隐藏其他分区
if ($("#secretContent").children().length == 0) {
$("#seemore").hide();
}
,这里是一个jsFiddle证明我的问题。当id为“secretContent”的div没有子/内容时,我有意隐藏ID为“seemore”的div。
任何帮助将不胜感激。提前致谢!
我有以下JS:如果div有没有内容隐藏其他分区
if ($("#secretContent").children().length == 0) {
$("#seemore").hide();
}
,这里是一个jsFiddle证明我的问题。当id为“secretContent”的div没有子/内容时,我有意隐藏ID为“seemore”的div。
任何帮助将不胜感激。提前致谢!
这是做的伎俩http://jsfiddle.net/chepe263/9Jmug/1/
if ($("#secretContent").children().length < 1) {
$("#seemore").hide();
}
在拨弄它显示的内容,因为它有内部secretContent
所以...你想用== 0
代替> 0
,我想。
的aditional的DIV你的意思'=== 0'? – 2012-04-23 16:44:25
不,我的意思是==。 'children()'总是返回一个整数,'0'显然是一个整数。绝对不需要在一个额外的'='符号上浪费一个字节。 – 2012-04-23 16:45:32
浪费整个字节?任何人如何处理这种开销!? – Zirak 2012-04-23 16:46:24
可能要改变你“大于”在平等的:
if ($("#secretContent").children().length == 0) {
$("#seemore").hide();
}
随着维加表明,如果你关心文本节点,而不是严格的孩子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();
}
}
我似乎无法得到与jsFiddle一起工作:/ – jacktheripper 2012-04-23 16:46:27
您可能正在寻找@维加的建议。如果你关心文本内容,你还需要将'children()'改为'content()'。 – 2012-04-23 16:47:13
@jacktheripper你的jsFiddle有文字内容。如果有一些内容/孩子,你想隐藏吗? – 2012-04-23 16:49:03
我觉得如果你要检查文本内容过多,你应该使用的.contents
代替.children
柜面。还将>
更改为==
。试着让我知道,
if ($("#secretContent").contents().length == 0) {
$("#seemore").hide();
}
这不起作用 – jacktheripper 2012-04-23 18:10:43
@jacktheripper你想达到什么目的? – 2012-04-23 18:11:25
替换 “> 0” 与 “== 0”
这应该做的伎俩!
我无法看到在我的例子中这是如何工作的。当你删除ID secretContent的div的内容,然后运行,带ID的div看起来更多保持显示,并不隐藏? – jacktheripper 2012-04-23 16:58:34
你的意思是? http://jsfiddle.net/chepe263/hmEgh/ – chepe263 2012-04-23 17:06:32
这是行得通的,但是当div – jacktheripper 2012-04-23 17:10:45