简体   繁体   English

如果内容与另一个单元格不同,则更改表格单元格的背景颜色

[英]Change the background colour of a table cell if the content is not the same as another cell

I have an output.php.我有一个 output.php。 It creates an html table with 3 columns: Question number, Correct Answer, Student Answer.它创建了一个包含 3 列的 html 表:问题编号、正确答案、学生答案。 Works just as I want it to.就像我想要的那样工作。

Now what I would like is to paint the cells with incorrect student answers red.现在我想要的是将学生答案不正确的单元格涂成红色。 I think Javascript is the best way to do this, rather than php.我认为 Javascript 是最好的方法,而不是 php。

Looking at other answers here, I was hoping this might do the job, but, alas...在这里查看其他答案,我希望这可以完成这项工作,但是,唉......

Can you please help me get this working?你能帮我解决这个问题吗?

<script type="text/javascript" >
function paint_cells() {
    var tds = document.querySelectorAll('tbody td'), i;
    for(i = 0; i < tds.length; i += 3) {
      if(tds[i+1].textContent != tds[i+2].textContent){
        tds[i+2].bgColor = "red";
      }
    }
</script>

I think you need to wait for page DOM loaded, try below.我认为您需要等待页面 DOM 加载,请尝试以下操作。 And it also depends on how and when the table in your page is generated, if it doesn't work, please provide more details.而且它还取决于您页面中的表格是如何以及何时生成的,如果它不起作用,请提供更多详细信息。

<script type="text/javascript" >
    
    window.addEventListener('DOMContentLoaded', (event) => {
        var tds = document.querySelectorAll('tbody td'), i;
        for(i = 0; i < tds.length; i += 3) {
          if(tds[i+1].textContent != tds[i+2].textContent){
            tds[i+2].bgColor = "red";
          }
        }
    });
</script>

You code working good.你的代码工作得很好。 I think your problem occurs that your js run before the dom already loaded.我认为你的问题发生在你的 js 在 dom 已经加载之前运行。 You have multiple opportunities to fix this.你有很多机会来解决这个问题。 1) you can add your script to the bottom inside the body tag. 1)您可以将脚本添加到 body 标签内的底部。 2) work with onload event. 2) 使用 onload 事件。 https://developer.mozilla.org/de/docs/Web/API/GlobalEventHandlers/onload https://developer.mozilla.org/de/docs/Web/API/GlobalEventHandlers/onload

Note Maybe you forgot to call the function?注意也许您忘记拨打 function? paint_cells()

 function paint_cells() { var tds = document.querySelectorAll('tbody td'), i; for(i = 0; i < tds.length; i += 3) { if(tds[i+1].textContent.= tds[i+2].textContent){ tds[i+2];bgColor = "red"; } } } paint_cells();
 <table border="1"> <thead> <tr> <th>Question</th> <th>Correct Answer</th> <th>Students Answer</th> </tr> </thead> <tbody> <tr> <td>abc</td> <td>right</td> <td>false</td> </tr> <tr> <td>abc</td> <td>right</td> <td>right</td> </tr> <tr> <td>abc</td> <td>right</td> <td>false</td> </tr> </tbody> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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