gpt4 book ai didi

javascript - 动态改变特定div的颜色

转载 作者:行者123 更新时间:2023-11-28 17:52:00 27 4
gpt4 key购买 nike

我想相应地更改 div 颜色,如果可能的话动态更改,这是我到目前为止所拥有的:

我的数据库:形状

id is_success
id1 0
id2 1
id3 0
id4 1

<div class="container" style="background: black; width: 500px; height: 500px;">

<div style ="id="id1" width: 35%; height: 14%; margin:20%"> div1 </div>
<div style ="id="id1" width: 35%; height: 14%; margin:80%"> div2 </div>
<div style ="id="id1" width: 35%; height: 14%; margin:10%"> div3 </div>
<div style ="id="id1" width: 35%; height: 14%; margin:60%"> div4 </div>

</div>

<?php
$sql = "SELECT * FROM shape ";

if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$id = $row['id'];
$is_success = $row['is_success'];
if ($is_success == 1)
{
//change the divs background color to green
}else {
//change the divs background color to red
}
}
}


最终结果应该是这样的:

enter image description here

因此,当数据库中的值发生更改时,应该设置 div 的背景颜色,这可能吗更新:请注意,每个 div 位于 html 页面上的不同位置

最佳答案

<div class="container" style="background: black; width: 500px; height: 500px;">
<div style ="id="id1" width: 35%; height: 14%;"> div1 </div>
<div style ="id="id1" width: 35%; height: 14%;"> div2 </div>
<div style ="id="id1" width: 35%; height: 14%;"> div3 </div>
<div style ="id="id1" width: 35%; height: 14%;"> div4 </div>
</div>

<?php
$sql = "SELECT * FROM shape ";

if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$id = $row['id'];
$is_success = $row['is_success'];
if ($is_success == 1)
{
echo "<script>$('#id$id').css('color', 'green')</script>";
}else {
echo "<script>$('#id$id').css('color', 'red')</script>";
}
}
}

或者您根本不必使用 jQuery 或 JavaScript。只需将 HTML 放入循环内即可。

<div class="container" style="background: black; width: 500px; height: 500px;">
<?php
$sql = "SELECT * FROM shape ";

if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$id = $row['id'];
$is_success = $row['is_success'];
if ($is_success == 1)
{
echo "<div id=\"id$id\" style=\"width: 35%; height: 14%; color: green\"> div$id </div>";
}else {
echo "<div id=\"id$id\" style=\"width: 35%; height: 14%; color: red\"> div$id </div>";
}
}
}
?>
</div>

关于javascript - 动态改变特定div的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45295408/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com