简体   繁体   中英

Changing text colour with CSS in jQuery

I am displaying results of a quiz and want it to show a green correct or a red incorrect beside the corresponding question. I have a PHP file holding the questions, that returns true or false depending on whether the users answer was correct or not. My code below shows how my results are shown (in a table, with true or false being shown). I've tried an if statement to say if that field equals true, make it green, else red. But nothing works. I just want to transform 'true' into a green 'correct' and 'false' into a red incorrect using jQuery.

Related JavaScript code:

$("#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");
    }
})

Related HTML code:

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

Also 'extendedResults' is an array that each question and chosen answer are pushed to. Any help would be appreciated. Thanks!

Try using last:child Selector - $("#tblextendedresults tbody tr:last-child td:last-child")

$(this) in your code does not refer the appropriate element.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM