2009-09-22 82 views
2

我有以下脚本,我无法找到如何使用汽车[0] ['img']内的值$('#img2')。attr('src ”,车[0] [ 'IMG']); 即时通讯JS的noob所以请解释我..为什么jQuery不会接受2d数组作为字符串值和运行该功能,以及我的问题可能的解决方案是什么?jquery atrr +二维数组问题

var id = 0 ; 
      var car = new Array(); 
      car[0]['img'] = "./images/carousel_img_2.jpg"; 
      car[0]['title'] ="title"; 
      car[0]['desc'] = 'longer description goes here'; 
      car[0]['link'] = "http://goeshere.com"; 
      car[1]['img'] = "./images/carousel_img_3.jpg"; 
      car[1]['title'] ='title'; 
      car[1]['desc'] = 'longer description goes here'; 
      car[1]['link'] = "http://goeshere.com"; 
      car[2]['img'] = "./images/carousel_img_2.jpg"; 
      car[2]['title'] ='title'; 
      car[2]['desc'] = 'longer description goes here'; 
      car[2]['link'] = "http://goeshere.com"; 


      function nxt() { 
     $('#img2').fadeOut('slow', function(){ 

      var img = car[i]['img'] ; 
      $('#img2').attr('src',img); 
     }); 
     $('#img2').fadeIn('slow'); 

      } 

回答

3

JavaScript有数组和字典不同的数据类型(键/值存储花哨名词,像数组或者通过数组定义关联数组()构造函数(如你所做的那样)或者通过方括号[],而字典与花括号{}中定义

阵列的一个例子:

var array = ['one', 'two', 'three]; 
alert (array[0]); // "one"; 

一dictioanry的例子:

var dict = { 
    'one': 'one one', 
    'two': 'two two', 
    'three': 'three three' 
} 
alert(dict.one); // "one one" 

尝试重新加工您的数组定义了一下:

var car = [ 
    { 
     'img': './images/carousel_img_2.jpg', 
     'title': 'title', 
     'desc': 'longer description goes here', 
     'link': 'http://goeshere.com' 
    }, 
    { 
     'img': './images/carousel_img_3.jpg', 
     'title': 'title', 
     'desc': 'longer description goes here', 
     'link': 'http://goeshere.com' 
    }, 
    { 
     'img': './images/carousel_img_2.jpg', 
     'title': 'title', 
     'desc': 'longer description goes here', 
     'link': 'http://goeshere.com' 
    } 
]; 
alert(car[0].img); // "./images/carousel_img_2.jpg" 
+1

也被称为JavaScript Object Notation :) – 2009-09-22 00:38:06

+1

正确!更多信息:http://www.json.org – 2009-09-22 00:42:40

+0

我改变了我的数组的定义后,它像一个魅力工作:)谢谢! – Aviatrix 2009-09-22 00:46:19

0

首先,摆脱你的img网址前面的./。我怀疑这是你目前麻烦的来源,但它不会在以后帮助你。只需放下正斜杠并按照“images/blah/blah.png”进行操作即可。

接下来,i是为那个nxt()函数定义的?现在我看到id在顶部设置为0,但没有声明i。即使你的意图是使它id我不确定它会工作,因为你没有在函数内迭代它。

我相信你想要的东西,如:。

function nxt (i) { 
    $('#img2').fadeOut('slow', function(){ 
      var img = car[i]['img'] ; 
      $('#img2').attr('src',img); 
    }); 
    $('#img2').fadeIn('slow'); 

} 
+0

我在剧本的开头声明,但仍然不工作..我删除了即使./ – Aviatrix 2009-09-22 00:42:47

+0

第一次使用它吗?尝试在声明该变量后添加'alert(img)'。看看它发出了多少次警示以及每次警示的价值。就像我上面所说的那样,根据你的代码,你似乎没有正确地迭代。 – Anthony 2009-09-22 01:09:09