簡體   English   中英

在jQuery中使用CSS更改文本顏色

[英]Changing text colour with CSS in jQuery

我正在顯示測驗的結果,並希望它在相應問題旁邊顯示綠色正確或紅色錯誤。 我有一個包含問題的PHP文件,該文件根據用戶的回答是否正確而返回true或false。 下面的代碼顯示了如何顯示我的結果(在表中顯示為true或false)。 我已經嘗試過if語句來說該字段是否等於true,使其變為綠色,否則變為紅色。 但是沒有任何效果。 我只想使用jQuery將“ true”轉換為綠色“正確”,將“ false”轉換為紅色不正確。

相關的JavaScript代碼:

$("#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”是一個數組,每個問題和選定的答案都被推送到該數組。 任何幫助,將不勝感激。 謝謝!

嘗試使用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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM