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

length プロパティを確認することで、要素が存在するかどうかを確認できます。

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

$ function の結果が空かどうかだけをチェックしてみませんか? ;) そうすれば、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 に答える