我想使用 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=change) 中工作正常,但在第二个 div 中,当我单击 class=red 的 div 时,它会更改第一个 div 而不是第二个。
我怎样才能让它改变它下面的div?
问题已解决:
http://jsfiddle.net/wjp4pqw6/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;}
希望这有帮助。
关于javascript - 使用 php 包含多个 javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25470213/