正在从列表元素中创建javascript对象

Creating javascript objects out of list elements

本文关键字:创建 javascript 对象 列表元素      更新时间:2023-09-26

我在无序列表中创建列表项之外的对象时遇到了一个小问题。我正在创建一个库,我需要每个库缩略图都是它自己的对象,所以我使用jQuery的$.each()迭代每个列表项

问题是我不知道如何给每个对象/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;
        });
    });
不要将galleryButton存储到"this"变量中。制作一个新的var,
var myGalleryButton = new galleryButton();

并更新您的作业:

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

然后在.each()函数的末尾,将myGalleryButton推送到一个数组/对象,以便稍后访问。

这没有任何意义:

   $('.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是实例名称,但它只存在于每个回调函数的函数范围内。

现在,如果你需要能够访问这些对象,那么你要么需要在函数之外创建变量,要么把它们放在其他可以访问的地方。如果是我,我会把它们存储在data中,用于li,比如:

        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')一样访问它们。