Reputation: 731
I want to call the function fill() with a variable as parameter. Everytime next() is called, the number of the variable should increase. So first, fill( q1 ) is called, then fill( q2 ) and so on. But apparently, you can't use variables as parameters. Any ideas?
var q1 = [2, "ff", "dd", "ss", "hh"];
var q2 = [2, "ff", "dd", "ss", "hh"];
var fill = function( data ) {
$( "#number" ).html( data[1]);
$( "#cat" ).html( data[2]);
$( "#ques span" ).html( data[3]);
$( "#answ .answ:nth-child(1) button" ).html( data[4]);
$( "#answ .answ:nth-child(2) button" ).html( data[5]);
$( "#answ .answ:nth-child(3) button" ).html( data[6]);
$( "#answ .answ:nth-child(4) button" ).html( data[7]);
$( "#answ .answ:nth-child(" + data[0] + ") button" ).attr( "data-state", "correct" );
}
var count = 1;
function next() {
fill( "q" + count );
count++;
}
Upvotes: 0
Views: 77
Reputation: 4659
I would think a better approach is to make a multi-dimensional array q
, in stead of q1
and q2
etc.
var q = [];
q[0] = [2, "ff", "dd", "ss", "hh"];
q[1] = [2, "ff", "dd", "ss", "hh"];
var fill = function( data ) {
$( "#number" ).html( data[1]);
$( "#cat" ).html( data[2]);
$( "#ques span" ).html( data[3]);
$( "#answ .answ:nth-child(1) button" ).html( data[4]);
$( "#answ .answ:nth-child(2) button" ).html( data[5]);
$( "#answ .answ:nth-child(3) button" ).html( data[6]);
$( "#answ .answ:nth-child(4) button" ).html( data[7]);
$( "#answ .answ:nth-child(" + data[0] + ") button" ).attr( "data-state", "correct" );
}
var count = 0;
function next() {
fill( q[count] );
count++;
}
This way, you could also check that you're not passing undefined
to fill()
:
function next() {
if (count < q.length) {
fill( q[count] );
count++;
}
}
Upvotes: 2
Reputation: 26360
If you call fill( "q"+count )
, the function will receive "q1" as a string.
If you want to pass the actual value of q1, you can use fill( eval("q"+count) )
Upvotes: 0