这项工作应该很容易,但我错过了一些。。。我从数据库中读取了一个变量,需要一个div来根据变量值更改颜色。
我也会欣赏缩短剧本的想法。感谢
<script language="Javascript" type="text/javascript">
function setColor(status){
var a= status;
if (a == "tag1") {
document.getElementById("status").style.backgroundColor = "red";
} ;
elseif (a == "tag2") {
document.getElementById("status").style.backgroundColor = "black";
} ;
}
</script>
<?php
$general=mysql_query("SELECT * FROM general ORDER BY `id` DESC LIMIT 0, 200;");
$n=mysql_numrows($general);
$i=0;
while($i<$n) {
$status=mysql_result($general,$i,"status");
echo '<div id="row">
<div class="celln" id="status" name="status">'.$status.'</div>
<script type="text/javascript">
setColor("<?php echo $status; ?>");
</script>
</div>';
$i++;
};
?>
为什么不
<style>
.tag1 { background-color:red }
.tag2 { background-color:black }
</style>
...
echo '<div class="celln '.$status.'" id="status">'.$status.'</div>';
分区没有的名称属性
正如@Saty所指出的,mysql_*
函数套件现在已被弃用,因此mysqli或PDO是前进的方向。
除非特别需要使用Javascript根据数据库中的一些值设置每个div的背景颜色,为什么不将css与PHP结合使用呢?
<style>
.red{color:white;background:red;}
.blue{color:white;background:blue;}
.white{color:black;background:white;}
.black{color:yellow;background:black;}
</style>
<?php
$conn=new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql='select * from `general` order by `id` desc limit 0, 200;';
$res=$conn->query( $conn, $sql );
if( $res ){
function getclass($status){
switch( $status ){
case 'tag1': return 'red';
case 'tag2': return 'black';
case 'tag3':return 'blue';
default: return 'white';
}
}
$i=0;
while( $rs=$res->fetch_object() ){
$i++;
$class=getclass( $rs->status );
echo '
<div id="row'.$i.'">
<div class="celln '.$class.'">'.$status.'</div>
</div>';
}
}
$conn->close();
?>