如果一个单独的div为空,我正在尝试删除一个特定的div.这是我正在使用的:
$(document).ready(function () {
if ('#leftmenu:empty') {
$('#menuTitleWrapper').remove();
$('#middlemenu').css({ 'right': '0', 'position': 'absolute' });
$('#PageContent').css({ 'top': '30px', 'position': 'relative' });
}
});
Run Code Online (Sandbox Code Playgroud)
我认为这很接近,但我无法弄清楚如何编写代码以测试#leftmenu是空的.任何帮助表示赞赏!
use*_*716 257
你可以用.is().
if( $('#leftmenu').is(':empty') ) {
// ...
Run Code Online (Sandbox Code Playgroud)
或者您可以测试该length属性以查看是否找到了一个.
if( $('#leftmenu:empty').length ) {
// ...
Run Code Online (Sandbox Code Playgroud)
请记住,空也意味着没有空格.如果有可能存在空格,那么您可以使用$.trim()并检查内容的长度.
if( !$.trim( $('#leftmenu').html() ).length ) {
// ...
Run Code Online (Sandbox Code Playgroud)
Dav*_*ang 34
这取决于你的意思是空的.
检查是否没有文本(这允许子元素自己为空):
if ($('#leftmenu').text() == '')
Run Code Online (Sandbox Code Playgroud)
要检查是否没有子元素或文本:
if ($('#leftmenu').contents().length == 0)
Run Code Online (Sandbox Code Playgroud)
要么,
if ($('#leftmenu').html() == '')
Run Code Online (Sandbox Code Playgroud)
小智 18
如果你想快速演示如何检查空div,我建议你试试这个链接:
http://html-tuts.com/check-if-html-element-is-empty-or-has-children-tags/
下面是一些简短的例子:
使用CSS
如果你的div是空的,甚至没有任何空格,你可以使用CSS:
.someDiv:empty {
display: none;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,没有CSS选择器可以选择前一个兄弟元素.只有下一个兄弟元素:x ~ y
.someDiv:empty ~ .anotherDiv {
display: none;
}
Run Code Online (Sandbox Code Playgroud)
使用jQuery
使用text()函数检查元素的文本长度
if ( $('#leftmenu').text().length == 0 ) {
// length of text is 0
}
Run Code Online (Sandbox Code Playgroud)
检查元素中是否有任何子标记
if ( $('#leftmenu').children().length == 0 ) {
// div has no other tags inside it
}
Run Code Online (Sandbox Code Playgroud)
检查空元素是否有空格
if ( $.trim( $('.someDiv').text() ).length == 0 ) {
// white-space trimmed, div is empty
}
Run Code Online (Sandbox Code Playgroud)
Ari*_*rif 10
您可以 像这样扩展jQuery功能:
延伸:
(function($){
jQuery.fn.checkEmpty = function() {
return !$.trim(this.html()).length;
};
}(jQuery));
Run Code Online (Sandbox Code Playgroud)
使用 :
<div id="selector"></div>
if($("#selector").checkEmpty()){
console.log("Empty");
}else{
console.log("Not Empty");
}
Run Code Online (Sandbox Code Playgroud)
你也可以使用这个:
if (! $('#leftmenu').children().length > 0 ) {
// do something : e.x : remove a specific div
}
Run Code Online (Sandbox Code Playgroud)
我想这对你有用!