am new to jquery. i have some colors inside of a div. if i click on any one of color it should affect on another div's background color.i'm getting these colors from database. how to make it?
ex:
<?php
$result = dbclass::convert_array($res);// retrieving colors here
for($i = 0; $i < $rows; $i++)
{ ?>
<div id="Color" style="background-color:<?php echo $result[$i][1];?>; width:32px; height:26px;" onclick="changeColor(<?=$result[$i][1];?>)">
</div>
<?
}
?>
<div id="changableColor" style"background-color:#FFFFFF;"> </div>
function changeColor(newColor)
{
$(#changableColor) // then how to write?
}
i need to change the background color of "id=changable开发者_运维问答Color".intially it have white background color?
Thanks.
The first 6 lines of your code are extremely hard to read so I rewrote them. You were mixing <?php
and <?
which isn't good practice and the style of for loop
that you should use when switching between HTML
and PHP
has been changed, too. A lot of this is preference, though, so feel free to disagree or change it back.
<?
$result = dbclass::convert_array($res);
$rows = count($result);
for ($i = 0; $i < $rows; $i++) :
?>
<div id="Color"
style="background-color:<? echo $result[$i][1];?>; width:32px; height:26px;"
onclick="changeColor(<? echo $result[$i][1]; ?>)">
</div>
<?
endfor;
?>
function changeColor(newColor) {
$('#changableColor').css('background-color', '#' + newColor);
}
$("#changableColor").css("backgroundColor","#colorCode");
$("#changableColor").css("background","#fff");
HERE is an example
There are a multitude of problems in your code. Firstly, inside your for loop you use an ID instead of a class, you should only use an ID once. Secondly, there are better ways to attach this. Please accept below and untested example, it should work, but will need some testing.
<?php
$result = dbclass::convert_array($res); //retrieving colors here
for($i = 0; $i < $rows; $i++) {
?>
<!-- Using class .color instead of ID -->
<div class="color" style="background-color:<?php echo $result[$i][1];?>; width:32px; height:26px;">
</div>
<? } ?>
<div id="changableColor" style"background-color:#FFFFFF;"> </div>
<script type="text/javascript">
$(document).ready(function(){
// Attaching using a jQuery click function
$(".color").click(function(){
// Using this operator to grab the background-color of the clicked item
$(#changableColor).css("background-color",$(this).css("background-color"))
});
});
</script>
Please comment if you need further help.
精彩评论