JQuery atrr + 2D error
I have the following script and I cannot find out how to use the value inside car [0] ['img'] inside this $ ('# img2'). attr ('src', car [0] ['IMG']); im a JS noob so please explain to me .. why does jquery not accept a 2d array as a string value and run this function and what is a possible solution to my problem?
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');
}
source to share
JavaScript has separate datatypes for arrays and dictionaries (a fancy term for key / value stores such as associative arrays. Arrays are defined either through the Array () constructor (like you) or square brackets [], and dictionaries are defined with curly brackets {}.
Array example:
var array = ['one', 'two', 'three];
alert ( array[0] ); // "one";
An example of a dictatorship:
var dict = {
'one': 'one one',
'two': 'two two',
'three': 'three three'
}
alert( dict.one ); // "one one"
Try redefining the array a bit:
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"
Get rid of the. / In front of your urls first img
. I doubt this is the source of your current problems, but it won't help you later. Just remove the slash and go to " images/blah/blah.png
".
Next, where i
is this function defined nxt()
? Right now I can see that is id
set to 0 at the top, but not declared i
. Even if you wanted to do this id
, I'm not sure if it will work, since you are not executing it inside a function.
I believe you want something like:
function nxt (i) {
$('#img2').fadeOut('slow', function(){
var img = car[i]['img'] ;
$('#img2').attr('src',img);
});
$('#img2').fadeIn('slow');
}
source to share