如意工具箱吧 关注:12贴子:348
  • 1回复贴,共1

求助求助!怎样给每个div添加点击事件!

只看楼主收藏回复

代码如下:
<html>
<head>
</head>
<body>
<script type="text/javascript">
function $(id) {
return document.getElementById(id);
}
var i, j;
var time;
var number = 0;
for (i = 1; i < 11; i++) {
for (j = 1; j < 11; j++) {
var div = document.createElement("div");
div.style.cssText = "width:40px;height:40px;position:absolute;border:5px solid black;";
div.style.top = i * 42 + 'px';
div.style.left = j * 42 + 'px';
div.id = i + "" + j;
//div.style.backgroundColor =
document.body.appendChild(div);
}
}
var oDiv = document.getElementsByTagName("div");
for (var i = 0; i < oDiv.length; i++) {
oDiv[i].style.backgroundColor = "white";
document.onclick = function a() {
oDiv[0].style.backgroundColor = "blue";
document.onclick = function () {
oDiv[0].style.backgroundColor = "green";
document.onclick = function () {
oDiv[0].style.backgroundColor = "red";
document.onclick = function () {
oDiv[0].style.backgroundColor = "white";
document.onclick = function () {
a();
}
}
}
}
}
}
</script>
</body>
</html>


1楼2014-12-09 08:59回复
    <html>
    <head>
    </head>
    <body>
    <script type="text/javascript">
    function $(id) {
    return document.getElementById(id);
    }
    var i, j;
    var time;
    var number = 0;
    for (i = 1; i < 11; i++) {
    for (j = 1; j < 11; j++) {
    var div = document.createElement("div");
    div.style.cssText = "width:40px;height:40px;position:absolute;border:5px solid black;";
    div.style.top = i * 42 + 'px';
    div.style.left = j * 42 + 'px';
    div.id = i + "" + j;
    //div.style.backgroundColor =
    document.body.appendChild(div);
    }
    }
    var oDiv = document.getElementsByTagName("div");
    for (var i = 0; i < oDiv.length; i++) {
    oDiv[i].style.backgroundColor = "white";
    oDiv[i].onclick = function () {
    this.style.backgroundColor = "blue";
    }
    }
    </script>
    </body>
    </html>


    IP属地:上海2楼2015-01-05 07:53
    回复