0

サイトのドロップダウンメニューを作成していて、要素のインスタンスに含まれるセクションの数に応じて、親div(.drop-down)の幅を変更しようとしています。.drop-downのインスタンスは合計7つあり、それぞれに3つ以下1つ以上の異なる量のセクションが含まれています。これが私のコードです。

    $('.drop-down').each(function(index) {
    var numSections = $(this).find('section').length;

        if (numSections = 1) {
            $('.drop-down').css('width','300px');
        }

        else if (numSections = 2) {
            $('.drop-down').css('width','600px');
        }

        else
            $('.drop-down').css('width','840px');
    });

どんな助けでも大歓迎です。

4

2 に答える 2

0

.drop-downどのクラスをターゲットにするかは指定しません。試してみてください$(this)

$('.drop-down').each(function(index) {
    var numSections = $(this).find('section').length;

        if (numSections = 1) {
            $(this).css('width','300px');
        }

        else if (numSections = 2) {
            $(this).css('width','600px');
        }

        else
            $(this).css('width','840px');
    });

次のように、新しい幅を文字列ではなく整数として宣言することもできます。

$(this).css('width',840);

編集:これが基本的なjsFiddleです:http://jsfiddle.net/MFfgj/

于 2012-09-06T14:22:16.880 に答える
0
$('.drop-down').each(function(index)
{
    var numSections = $(this).find('section').length;

    if (numSections == 1) {
        $(this).css('width', 300);
    }
    else if (numSections == 2) {
        $(this).css('width', 600);
    }
    else if (numSections == 3){
        $(this).css('width', 840);
    }
});
于 2012-09-06T14:45:28.693 に答える