使用php包含多个javascript代码

时间:2014-08-24 09:17:22

标签: javascript html

我想使用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/

2 个答案:

答案 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)
        });
    });
});