2

HTML:

<div class="parent">
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
</div>

jQuery

parentWidth = $(".parent").outerWidth(true);
oneWidth = $(".parent .one").outerWidth(true);
twoWidth = $(".parent .two").outerWidth(true);
$('.parent .three').width( parentWidth - oneWidth - twoWidth);

但问题是,有时 DIV .one 或 .two 可能不存在,我该如何修改 jQuery 呢?

谢谢

4

3 回答 3

6

您可以通过检查元素的长度属性来检查元素是否存在:

parentWidth = $(".parent").outerWidth(true);
oneWidth = $(".parent .one").length ? $(".parent .one").outerWidth(true):0;
twoWidth = $(".parent .two").length ? $(".parent .two").outerWidth(true):0;
$('.parent .three').width( parentWidth - oneWidth - twoWidth);
于 2010-01-24T16:39:58.077 回答
4

你为什么不检查 $ 函数的结果是否为空?;) 这样您就可以轻松找出 div 是否存在,并在这种情况下简单地将宽度设置为 0,例如

oneDiv = $(".parent .one");
oneWidth = oneDiv.length == 0 ? 0 : oneDiv.outerWidth(true);
于 2010-01-24T16:28:51.010 回答
3

试试这个代码:

var third = $('.parent .three');
var wantedWidth = third.parent().outerWidth(true);

third.siblings().each(function(){
    wantedWidth -= $(this).outerWidth(true);
});

third.width(wantedWidth);
于 2010-01-24T17:04:27.943 回答