2016-09-11 9 views
0

퀴즈 결과를 표시하고 해당 질문 옆에 녹색이 맞거나 빨간색이 틀리길 원합니다. PHP 파일을 질문을 들고, true 또는 false 사용자가 대답을 맞는지 여부에 따라 반환합니다. 내 코드는 내 결과가 어떻게 표시되는지 보여줍니다 (표에 true 또는 false가 표시됨). 해당 필드가 true이면 녹색으로, 그렇지 않으면 빨간색으로 if 문을 시도했습니다. 그러나 아무것도 작동하지 않습니다. 난 그냥 '사실'녹색으로 '올바른'및 '잘못된'빨간색 jQuery를 사용하여 잘못된 변환 할 싶어요.jQuery에서 CSS로 텍스트 색상 변경

관련 자바 스크립트 코드 :

$("#tblextendedresults tbody").prepend("<br>") 
$.each(extendedResults, function(i) { 
    $("#tblextendedresults tbody").append("<tr><td>" + extendedResults[i]["question"] + "</td><td>" + extendedResults[i]["your_answer"] + "</td><td>" + extendedResults[i]["correct"] + "</td></tr>") 
    if (extendedResults[i]["correct"] == "true") { 
     $(this).css("color", "green"); 
    } 
    else { 
     $(this).css("color", "red"); 
    } 
}) 

관련 HTML 코드 :

<table id="tblextendedresults"> 
    <thead> 
     <th>Question</th> 
     <th>Your answer</th> 
     <th>Correct?</th> 
    </thead> 
    <br> 
    <tbody></tbody> 
</table> 

또한 'extendedResults가'는 각각의 질문 선택한 답이 푸시되는 배열입니다. 도움이 될 것입니다. 감사!

+1

의 jQuery CSS를, 당신은 $ (이) 실제 필드임을 확인할 수 있습니까? – ArturoO

+0

@ArturoO 그 if 문은 틀렸다고 믿습니다. "extendedResults [i] ["correct "]는 대답이 맞는지 아닌지에 따라 적절한 true/false를 반환하지만 if 문은이 반환을 전혀 변경하지 않습니다. 또한 텍스트를 변경하는 방법을 알지 못합니다 to true true 대신 correct – Brittany

답변

3

last:child 선택기를 사용해보십시오 - 코드에서 $("#tblextendedresults tbody tr:last-child td:last-child")

$(this) 적절한 요소를 참조하지 않습니다. 코드가 잘 보이는()

JSFiddle

var extendedResults = [{ 
 
    "question": "Question1", 
 
    "your_answer": "your_answer1", 
 
    "correct": true 
 
}, { 
 
    "question": "Question2", 
 
    "your_answer": "your_answer2", 
 
    "correct": false 
 
}, { 
 
    "question": "Question3", 
 
    "your_answer": "your_answer3", 
 
    "correct": true 
 
}]; 
 

 
$("#tblextendedresults tbody").prepend("<br>") 
 

 
$.each(extendedResults, function(i) { 
 
    $("#tblextendedresults tbody").append("<tr><td>" + extendedResults[i]["question"] + "</td><td>" + extendedResults[i]["your_answer"] + "</td><td>" + extendedResults[i]["correct"] + "</td></tr>") 
 

 
    if (extendedResults[i]["correct"] == true) { 
 
    $("#tblextendedresults tbody tr:last-child td:last-child").css("color", "green").html("Correct"); 
 
    } else { 
 
    $("#tblextendedresults tbody tr:last-child td:last-child").css("color", "red").html("Incorrect"); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<table id="tblextendedresults"> 
 
    <thead> 
 
    <th>Question</th> 
 
    <th>Your answer</th> 
 
    <th>Correct?</th> 
 
    </thead> 
 
    <br> 
 
    <tbody></tbody> 
 
</table>

+0

대단히 고마워! 이런 경우가 있을지 모르지만 어떻게해야할지 모르겠다. 'true'요소를 만들 수 있는지에 대한 생각은 'correct'이고 'false' '요소가'틀린 '대신에 ..? – Brittany

+0

그냥'.html()'을 추가하면, 업데이트 된 답변보기 –