jQuery如果其他子div不存在,则使子div更大

时间:2012-07-03 12:08:37

标签: jquery width

我的HTML结构看起来像这样

<div class="container">
    <div class="image"><img /></div>
    <div class="title_body">
        <div class="title">Title</div>
        <div class="body">Body text</div>
    </div>
</div>

图像位于左侧,标题+正文位于图像右侧。

如果图像不存在,我想做的是使title_body div的宽度为100%。 有很多.container和我只想在容器中使用缺少的.image 100%div

4 个答案:

答案 0 :(得分:2)

如果(如标题所示)jQuery是另一种选择,您只需执行$('div.container:has(div.image)').addClass('has-img'),然后将div.container.has-imgdiv.container区别开来。

答案 1 :(得分:0)

$('.container:has(.title_body)').not(function() {
    return $(this).has('.image').length;
}).css('width', '100%');

不是通过jQuery手动设置宽度,而是可以添加一个执行此操作的类。

答案 2 :(得分:0)

如果真的是你想要的,你可以检查长度以查看img是否存在,如果你有多个,尝试使用each()

 if(!($(element).length)){ // if the element not exist
   // do something
 }

这是一个live demo


编辑:

这里有一个使用each()的例子,如果你有一个以上:

$(".image").each(function(){
   if(!($(this).children().length)){ // if img not exits
       $(this).next().width("100%");
   }
});

Live demo


编辑:检查div image

Live Demo 2

答案 3 :(得分:0)

$('.container').each(function(){
    if ($(this).has('.image').length == 0) {
        $(this).children('.title_body:first').css('width', '100%');
    }
});​

查看jsFiddle

上的示例