我在学校时间表上遇到了问题,它是用php/html编码的。课程被填充在一个html表格中(惊喜!!),填充的单元格必须获得背景颜色。问题是,表格是动态填充数据的,因此不可能为 td 标签提供背景色。这是我的代码:
echo"<td id='cell' style='width:15%'>";
foreach($plan->result as $res){
if($res->date == "20131007" && $item->startTime == $res->startTime){
foreach ($res->kl as $kl){
echo getKlasseById($ch, $kl->id).", ";
}
echo"<script type='"text/javascript'">
var td = document.getElementById('cell');
td.style.backgroundColor='#FF8000';</script>";
}
}
这样做是用背景色填充表格的第一个单元格,然后什么都没有(关于颜色)。
编辑
好的,我解决了我的问题。正如我的编程教授所说,我试图用聚变炸弹射击鸽子。我只是在具有所需背景颜色的 foreach 循环周围放了一个<div>
。无论如何,谢谢你的帮助。
创建一个具有所需背景颜色的 CSS 类:
.colored { background-color: yourcolor; }
并且,当您回显<td>
时,将类添加到其中。
如果这是主要问题,您可以在 if 中执行此操作,而不是在 if 之前渲染 td..
echo "<td id='"cell'" class='"colored'">";
更清楚的是,我的意思是而不是这个:
echo"<td id='cell' style='width:15%'>";
foreach($plan->result as $res){
if($res->date == "20131007" && $item->startTime == $res->startTime){
foreach ($res->kl as $kl){
echo getKlasseById($ch, $kl->id).", ";
}
echo"<script type='"text/javascript'">
var td = document.getElementById('cell');
td.style.backgroundColor='#FF8000';</script>";
}
}
您可以这样做:
foreach($plan->result as $res){
if($res->date == "20131007" && $item->startTime == $res->startTime){
echo"<td id='cell' style='width:15%' class='colored'>";
foreach ($res->kl as $kl){
echo getKlasseById($ch, $kl->id).", ";
}
}
else {
echo"<td id='cell' style='width:15%'>";
// Whatever goes into the else, if needed.
}
}
无论如何。。你不是要关<td>
吧?:)
为什么这样?为什么不使用PHP代替。所有这些 samll Javascript 元素只会减慢页面的速度,并使浏览器解析页面的速度变慢。PHP+ 某些类的效率更高
foreach($plan->result as $res){
$backgroundColor = "";
if($res->date == "20131007" && $item->startTime == $res->startTime){
foreach ($res->kl as $kl){
echo getKlasseById($ch, $kl->id).", ";
}
$backgroundColor = "#FF8000";
}
}
echo"<td id='cell' style='width:15%;background-color: ".$backgroundColor."'>";
小旁注:您的代码有点不清楚,所以我不确定我是否以正确的顺序或正确的语句放置代码,但您抓住了我的漂移