1

少し遅くなっているので、ばかげた間違いをしているのなら失礼します。何らかの理由で次のコード:

$(".myClass").each(function(){
    widths[$(this).attr("id")] = $(this).width();   
    if ($(this).attr("id")  != $(clickedExpand).attr("id"))
    {
        $(this).animate({
            width: '10px'
        });
    }

});

配列は次のように初期化されます

var widths = new Array();

コードの前半。何らかの理由で、アニメーションが始まる前に幅を記録しているにもかかわらず、配列にアニメーション後の値が表示されています。アニメーションが終了し、値が記録されているように見えます。関数から取り出して別の.eachでラップしようとしましたが、同じ結果が得られています。

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

コード全体:

var slateWidths = {};
$(".slateExpand").click(function(){
    var clickedExpand = $(this).closest(".slate");

    $(".slate").each(function(){
        slateWidths[$(this).attr("id")] = $(this).outerWidth();   
        if ($(this).attr("id")  != $(clickedExpand).attr("id"))
        {
            $(this).animate({
                width: '10px'
            });
            $(this).find($('.slateExpand')).hide();
        }

    });

    $(this).text("Restore");
    $(this).removeClass("slateExpand").addClass("slateRestore");
    $(".slateRestore").on("click",function(){

        $(".slate").each(function()
        {
            alert(slateWidths[$(this).attr("id")]);
            //var width = slateWidths[$(this).attr("id")];
            $(this).animate({
                width: slateWidths[$(this).attr("id")]
                });
        });
    });
});
4

2 に答える 2

1
// first of all save all widths for all .slate
var slateWidths = {};
$(".slate").each(function(){
    slateWidths[$(this).attr("id")] = $(this).width();
});

$(".slateExpand").click(function(){
    var $slate = $(this).closest('slate');    

    if($slate.hasClass('hidden')) {

        $slate.animate({
            width: slateWidths[$slate.attr('id')]
        });
        $(this).text("hide");
        $slate.removeClass("hidden")        
    }else{

        $slate.animate({
            width: '10px'
        });
        $(this).text("Restore");
        $slate.addClass("hidden")
    }    
});
于 2012-08-26T16:30:25.413 に答える
0

同様の問題が発生した場合は、簡単な解決策があります。問題は、クラスが変更されたにもかかわらず、クリックがdivからのイベントのバインドを解除されていないことです。その結果、最初に幅を記録するコードを再実行します。これにより、以前の幅が現在の幅と同じになるため、アニメーションが再生されなくなります。これを解決するには、単に追加します

   $("theDiv").unbind("click);

イベントハンドラーを削除します。これにより、前のクラスのクリックイベントが発生しなくなります。

于 2012-08-26T16:42:29.847 に答える