Jquery如果我的div是空的

时间:2013-02-06 16:21:33

标签: jquery css if-statement

我这里有这个脚本

<script type="text/javascript">
$(document).ready(function () {
    if($('.subhead').is(':empty')){
        $(this).css('background-color', 'none !important');
    }

});
</script>

我想在这里做的是说如果我的班.subhead是空的然后改变了背景颜色,我在代码中有多个.subhead div,如果我运行这样的脚本

<script type="text/javascript">
    $(document).ready(function () {
        if($('.subhead').is(':empty')){
            alert('hi');
        }else{
            alert('hello');
        }
    });
    </script>

它将返回Hello

我正在尝试做什么?

2 个答案:

答案 0 :(得分:5)

background-colour的默认设置为transparent,而非none。试试这个:

if ($('.subhead').is(':empty')){
    $(this).css('background-color', 'transparent !important');
}

答案 1 :(得分:2)

使用:empty作为选择器,因为您有多个.subhead元素,使用is并不能达到预期效果。您的代码表示如果所有匹配的.subhead类的元素都为空,则将所有匹配元素的background-color属性设置为none

$('.subhead:empty').css('background-color', 'none !important');