2015-04-23 237 views
0

我试图循环遍历一些项目,并创建一个数组。每个循环都应该是数组中的一个新项目,但我遇到了一些问题。似乎只有一组项目被添加,而不是多个。用循环填充对象数组

我试过下面的代码。请帮我解决它。

function OpenPopup3(src,type,title){ 

var myData = []; 
rows.each(function(index) { 
    var temp_obj = {}; 
    temp_obj["src"] = $this.find('.elementOne').text(), 
    temp_obj["type"] = $this.find('.elementTwo').text(), 
    temp_obj["title"] = $this.find('.elementThree').text() 
    myData.push(temp_obj); 
}); 

$.magnificPopup.open({ 
    key: 'my-popup', 
    items: myData, 
    type: 'inline', 
    inline: { markup: '<div class=""><div class="mfp-close"></div>'+'<img class="mfp-src">'+'<div class="mfp-title"></div>'+'</div>' }, 
    gallery: { enabled: true } 
}); 
} 

其实我要的是如下:

{ 
    src: "/googleimages/123/a.png", 
    type: "Stuff", 
    title: "Title1" 
}, 
{ 
    src: "/googleimages/123/b.png", 
    type: "Stuff", 
    title: "Title2" 
}, 
{ 
    src: "/googleimages/123/c.png", 
    type: "Stuff", 
    title: "Title3" 
} 
+0

你试图使用;而不是$ this.find('。elementTwo')。text() – SolidSnake

+1

你在哪里声明你正在循环的行变量?我相信它可能只有一个元素。 – Marquizzo

+0

你想要做的是创建一个对象数组。这与JSON无关。 JSON是**数据格式**,就像XML或CSV一样。 –

回答

0

首先是什么rows变量包含哪些内容?似乎没有在任何地方宣布。

第二你有语法错误:

temp_obj["src"] = $(this).find('.elementOne').text(); 
temp_obj["type"] = $(this).find('.elementTwo').text(); 
temp_obj["title"] = $(this).find('.elementThree').text(); 
+0

代码中没有语法错误。总的来说,这似乎更像是一条评论。 –