繁体   English   中英

将变量从php循环传递到javascript函数作为参数

[英]pass variable from php loop to javascript function as argument

这项工作应该很容易,但是我很想念...我从数据库中读取了一个变量,我需要一个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>';

div顺便说一句没有名称属性

如@Saty所述,现在不建议使用mysql_*函数集,因此mysqli或PDO是前进的方向。

除非特别需要使用Javascript根据db中的某个值来设置每个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();

?>

暂无
暂无

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

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