从列表元素中创建javascript对象
我在无序列表中创建列表项外的对象时遇到了一个小问题。我正在创建一个图库,我需要每个图库缩略图都是它自己的对象,所以我使用jQuery的$.each()遍历每个列表项 问题是我不知道如何为每个对象/li指定它自己的实例名 代码如下:从列表元素中创建javascript对象,javascript,jquery,html,oop,Javascript,Jquery,Html,Oop,我在无序列表中创建列表项外的对象时遇到了一个小问题。我正在创建一个图库,我需要每个图库缩略图都是它自己的对象,所以我使用jQuery的$.each()遍历每个列表项 问题是我不知道如何为每个对象/li指定它自己的实例名 代码如下: function galleryButton(){ this.link this.name this.image this.identifier, this.goPage = fu
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 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);
});
如果不想覆盖此,则需要创建一个新对象,如:
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
是实例名,但它只存在于每个回调函数的函数范围内
现在,如果您需要能够访问这些对象,那么您需要在函数外部创建变量,或者将它们放在其他可以访问的地方。如果是我,我会将它们存储在数据
中,用于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);
然后您可以像
$(SomeSelector或Togettheli)一样访问它们。数据('slide')
您不能分配给!!!如何使用$(someSelectToGetLI.data('slide')访问对象的属性?我会去$(thing.data('slide).link吗?是的,但是你应该始终确保你确实拥有这个对象-如果你还没有用.data
设置它,那么。data
将返回未定义的,因此直接使用.link
会抛出一个错误。比如:sliceObj=$(someSelectToGetLI.data('slide');if(slide){//执行slide.link}