2013-07-31 123 views
0

我有一个小问题,在无序列表中创建列表项目中的对象。我创建一个画廊,我需要为每个画廊缩略图,它是自己的对象,所以我遍历每个列表项使用jQuery的$ .each()从列表元素创建javascript对象

问题是我不知道如何给每个对象/它是它自己的实例名称。

下面的代码:

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; 
     }); 

    }); 
+0

你不能指定['this'关键字](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)!!! – Bergi

回答

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,你想创建一个像一个新的对象:所以在这种情况下slide

 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'); 

是实例名,但它只会在该函数的每个回调函数的范围内存在。

现在如果您需要能够访问这些对象,那么您需要在函数外创建变量或将它们放在其他地方可访问的位置。要不是我,我将它们存储在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')访问它们。

+0

如何使用$(someSelectToGetLI).data('slide)访问对象的属性?我会去$(东西).data('slide).link? – Optymystyc

+0

是的,但是您应该始终确保您确实拥有该对象 - 如果您没有使用.data设置它,那么'.data'将返回undefined,因此直接使用'.link'会引发错误。所以像这样:'sliceObj = $(someSelectToGetLI).data('slide');如果(幻灯片){//做类似slide.link}的东西'' – prodigitalson

1

您galleryButton不要存放到 “这个” 变量。创建一个新的变种,

var myGalleryButton = new galleryButton(); 

和更新的任务:

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

,然后在。每个()函数的末尾,推动myGalleryButton以供以后访问数组/对象。