PHP展示下拉列表,选项设置为数据库存储颜色进制,colorname是颜色名称,color是颜色进制
一、表结构
produce_info_nav1_colorshow
produce_info_nav1
二、核心代码
php">//查询对应默认颜色
$sql_selcolor = "SELECT color FROM produce_info_nav1_colorshow where colorname = '" . $myrow['color'] . "'";
$result_selcolor = DB_query($sql_selcolor, $db);
$row_selcolor = DB_fetch_array($result_selcolor);
$color_selcolor = $row_selcolor['color'];
//执行下拉列表
echo '<select onchange="changeBackgroundColor(this)" style="background-color:' . htmlspecialchars($color_selcolor) . '" type="text" required="required" name="color' . $myrow['id'] . '" id="color' . $myrow['id'] . '" value="' . htmlspecialchars($myrow['color']) . '">';
//sql查询全部颜色条
$sql_color = "SELECT colorname, color FROM produce_info_nav1_colorshow";
$result_color = DB_query($sql_color, $db);
//循环执行option
while ($v = DB_fetch_array($result_color)) {$selected = ($v['colorname'] == $myrow['color']) ? 'selected="selected"' : '';echo '<option style="background-color:' . $v['color'] . '" value="' . htmlspecialchars($v['colorname']) . '" ' . $selected . '>' . htmlspecialchars($v['colorname']) . '</option>';
}
echo '</select>';
另一种写法
<select onchange="changeBackgroundColor(this)" style="background-color:<?= $color_selcolor ?>" name="color<?= $j ?>" id="color<?= $j ?>"><?php$sql_color = "SELECT colorname, color FROM produce_info_nav1_colorshow order by id";$result_color = DB_query($sql_color, $db);// 初始化 $color_selcolor 为第一个查询结果的颜色名称$color_selcolor = '';if ($v = DB_fetch_array($result_color)) {$color_selcolor = $v['colorname'];}// 重新定位到查询结果的开始位置DB_data_seek($result_color, 0);while ($v = DB_fetch_array($result_color)) {$selected = ($v['colorname'] == $color_selcolor) ? 'selected="selected"' : '';?><option style="background-color:<?= $v['color'] ?>" value="<?= $v['colorname'] ?>" <?= $selected ?>><?= $v['colorname'] ?></option><?php}?>
</select>
<script>//下拉更换已选中后的颜色条function changeBackgroundColor(selectObj) {var selectedValue = selectObj.value;selectObj.style.backgroundColor = selectObj.options[selectObj.selectedIndex].style.backgroundColor;selectObj.style.color = selectedValue;}
</script>