2014-11-20 3 views
1

코드를 단축하고 싶습니다. 나는 퀴즈를 가지고 있으며 각 질문마다 대답이 적재됩니다. 그러나 나는 그것을 위해 변수를 갖고 싶다. 여기 변수를 JSON 키로 사용하십시오.

코드입니다 :

if (nr === 1) { 
    $('#questionmobile').html(content.inst3.question1); 
    $('#answer1').html(content.inst3.q1a1); 
    $('#answer2').html(content.inst3.q1a2); 
    $('#answer3').html(content.inst3.q1a3); 
    $('#answer4').html(content.inst3.q1a4); 
} else if (nr === 2) { 
    $('#questionmobile').html(content.inst3.question2); 
    $('#answer1').html(content.inst3.q2a1); 
    $('#answer2').html(content.inst3.q2a2); 
    $('#answer3').html(content.inst3.q2a3); 
    $('#answer4').html(content.inst3.q2a4); 
}...... 

당신은 매우 중복 볼 수 있듯이, 그래서 나는 질문의 수의 정보가 변수 "NR"를 포함하는 생각. 그것은 바로 JSON의 콘텐츠를 직접하지 않습니다 때문에 연결 +nr+가 작동하지

$('#questionmobile').html(content.inst3.question+nr); 
$('#answer1').html(content.inst3.q+nr+a1); 

: 그래서 내가 좋아하는 뭔가를 원한다.

답변

4

변수를 키로 사용하려면 대괄호 표기법 (예 : 배열, [])을 사용할 수 있습니다.

$('#questionmobile').html(content.inst3['question'+nr]); 
$('#answer1').html(content.inst3['q'+nr+'a1']); 

당신도 답을 루프를 사용할 수 있습니다 : 당신이 content.inst3.q+nr+a1을 말할 때 자바 스크립트가 함께 변수를 추가되도록 (content.inst3.q)+(nr)+(a1)으로, 즉 존재하지 않는 것으로 해석

$('#questionmobile').html(content.inst3['question'+nr]); 

var i, numAnswers = 4; 
for(i = 1; i <= numAnswers; i++) { 
    $('#answer' + i).html(content.inst3['q'+nr+'a'+i]); 
} 
1

첫째,.

질문에 대한 대답은 대괄호를 사용하여 개체의 필드에 문자열 이름으로 액세스 할 수 있다는 것입니다. 예 :

var x = {name: "Joe", age:56}; 
alert(x["name"]); //Outputs Joe 
alert(x["age"]); //Outputs 56 

이 기술을 사용하여 패턴과 일치하는 문자열을 작성할 수 있습니다. 그러나 이것이 아마도 최선의 방법은 아닙니다. 대신이 기술을 사용할 필요가 없도록 입력 데이터를 재구성해야합니다. 예를 들어 데이터를 다음과 같이 표시 할 수 있습니다.

{ 
    "questions": [ 
     { 
      "prompt": "Who was the first president of the US?", 
      "answers": ["George Washington", "Abraham Lincoln", "Captain America", "The Hulk"] 
     } 
    ] 
} 

이렇게하면 데이터가 배열로 구성되므로이 데이터의 사용 사례와 더 잘 어울립니다.

0

감사합니다. 두 답변 모두 도움이되었습니다. 내 솔루션은 귀하의 답변을 조합 한 것입니다.

$('#questionmobile').html(content.inst3.questions[nr - 1].question); 
var i, numAnswers = 3; 
for (i = 0; i <= numAnswers; i++) { 
$('#answer' + (i + 1)).html(content.inst3.questions[nr - 1].answers[i]); 
} 

그리고 내 JSON 구조 청소 :

"questions":[ 
{ 
     "question":"bla?", 
     "answers":["Toto Arno",'Anders Thomas','Tadao Ando','Tadaaa Anden'] 
}, 
{ 
     "question":'bli?', 
     "answers":["Wasser",'Papier','Stein','Schere'] 
}, 
{ 
     "question":'blu?', 
     "answers":["Deutschland",'Niederlande','Bosnien und Herzegowina','S&uuml;dkorea'] 
} 
      ] 
관련 문제