0

順序付けられていないリストのリスト項目からオブジェクトを作成する際に小さな問題があります。ギャラリーを作成していますが、各ギャラリーのサムネイルを独自のオブジェクトにする必要があるため、jQuery の $.each() を使用して各リスト項目を反復処理しています

問題は、各 object/li に独自のインスタンス名を付ける方法がわからないことです。

コードは次のとおりです。

    function galleryButton(){
        this.link
        this.name
        this.image
        this.identifier,
        this.goPage = function(){
        $('.container').animate({opacity : '0'}, 500).load(this.link + ' .galContainer', function(){$('.container').animate({opacity : '1'})});
        return false;
        }
    }

    $(document).ready(function(){
        $.ajaxSetup({
            cache:false
        });

        $('.gallery li a').each(function(node, value){
            this = new galleryButton();
            this.link = $(this).attr('href');
            this.name = $(this).attr('name');
            this.image = $(this + " img").attr('src');
            this.identifier = $(this).attr('data-pic-id');

            $(this).click(this.goPage);
        })

        $('.goback').click(function(){

            var back = $(this).attr('href');
            $('.container').animate({opacity : '0'}, 500).load(back + ' .gallery', function(){$('.container').animate({opacity : '1'})});
                return false;
        });

    });
4

2 に答える 2

1

galleryButton を「this」変数に保存しないでください。新しい変数を作成し、

var myGalleryButton = new galleryButton();

割り当てを更新します。

myGalleryButton.link = $(this).attr('href');
/// etc

そして、.each() 関数の最後で、後でアクセスできるように myGalleryButton を配列/オブジェクトにプッシュします。

于 2013-07-31T19:10:18.160 に答える
0

これは意味がありません:

   $('.gallery li a').each(function(node, value){
        this = new galleryButton();
        this.link = $(this).attr('href');
        this.name = $(this).attr('name');
        this.image = $(this + " img").attr('src');
        this.identifier = $(this).attr('data-pic-id');

        $(this).click(this.goPage);
    });

をオーバーライドしたくない場合thisは、次のような新しいオブジェクトを作成します。

        var slide = new galleryButton();
        slide.link = $(this).attr('href');
        slide.name = $(this).attr('name');
        slide.image = $(this + " img").attr('src');
        slide.identifier = $(this).attr('data-pic-id');

したがって、この場合slideはインスタンス名ですが、その関数の各コールバック関数のスコープ内にのみ存在します。

これらのオブジェクトにアクセスできるようにする必要がある場合は、変数を関数の外で作成するか、アクセス可能な別の場所に配置する必要があります。私だったら、次dataliように保存します。

        var slide = new galleryButton();
        slide.link = $(this).attr('href');
        slide.name = $(this).attr('name');
        slide.image = $(this + " img").attr('src');
        slide.identifier = $(this).attr('data-pic-id');
        $(this).closest('li).data('slide', slide);

その後、次のようにアクセスできます$(someSelectorToGetTheLI).data('slide')

于 2013-07-31T19:14:08.603 に答える