我想用变量作为参数调用函数 fill()。每次调用 next()时,变量的数量都应该增加。 首先,调用 fill(q1),然后 fill(q2),依此类推。但显然,你不能使用变量作为参数。有什么想法吗?
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++;
}
答案 0 :(得分:2)
我认为更好的方法是创建一个多维数组q
,而不是q1
和q2
等。
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++;
}
这样,您还可以检查是否未将undefined
传递给fill()
:
function next() {
if (count < q.length) {
fill( q[count] );
count++;
}
}
答案 1 :(得分:0)
如果您致电fill( "q"+count )
,该功能将会收到&#34; q1&#34;作为一个字符串。
如果您想传递q1的实际值,可以使用fill( eval("q"+count) )