我想使用php(include)在同一页面中多次包含此代码 HTML代码:
<div class="red" onclick="red()">red</div>
<div class="green" onclick="green()">green</div>
<div class="blue" onclick="blue()">blue</div>
<div id="change">click on the colors to change the div color</div>
css代码:
.red{background-color: red;width: 50px;}
.green{background-color: green;width: 50px;}
.blue{background-color: blue;width: 50px;}
#change{background-color: yellow;width: 100px;}
javascript代码:
function red()
{
document.getElementById('change').style.background="red";
}
function green()
{
document.getElementById('change').style.background="green";
}
function blue()
{
document.getElementById('change').style.background="blue";
}
此代码在第一个div(id =更改)中正常工作但在第二个div中,当我点击div = class = red时,它会更改第一个div而不是第二个div。
如何让它改变它下面的div?
问题解决了:
http://jsfiddle.net/wjp4pqw6/1/
答案 0 :(得分:1)
我已经写了一些应该为你做的代码:
<强> PHP 强>
for($i=0; $i<10; $i++) {
echo '<div id="containter_'.$i.'">';
echo '<div class="red" onclick="color(\'red\', this);" id="red_'.$i.'">red</div>';
echo '<div class="green" id="green_'.$i.'" onclick="color(\'green\', this)">green</div>';
echo '<div class="blue" id="blue_'.$i.'" onclick="color(\'blue\', this)">blue</div>';
echo '<div class="change" id="change_'.$i.'"></div>';
echo '</div>';
}
那个回声代码的10个块。
<强>的Javascript 强>
function color(c, elem) {
id = elem.id.replace(c,'');
document.getElementById('change'+id).style.background=c;
}
<强> CSS 强>
.red{background-color: red;width: 50px;}
.green{background-color: green;width: 50px;}
.blue{background-color: blue;width: 50px;}
.change{background-color: yellow;width: 100px;}
希望这有帮助。
答案 1 :(得分:0)
试试这个,
<强> HTML 强>
<div>
<div class="red">red</div>
<div class="green">green</div>
<div class="blue">blue</div>
<div class="change">click on the colors to change the div color</div>
</div>
<div>
<div class="red">red</div>
<div class="green">green</div>
<div class="blue">blue</div>
<div class="change">click on the colors to change the div color</div>
</div>
<强> CSS 强>
.red{background-color: red;width: 50px;}
.green{background-color: green;width: 50px;}
.blue{background-color: blue;width: 50px;}
.change{background-color: yellow;width: 100px;}
<强> JS 强>
$(function() {
var colors = ["red", "green", "blue"];
$.each(colors, function() {
var color = this;
$("." + color).click(function() {
$(this).siblings(".change").css("background", color)
});
});
});