如何通过单击JavaScript更改动态创建的div的背景?

时间:2014-12-18 12:32:24

标签: javascript html5

我正在使用我创建的两个按钮在'main'标签中添加和删除div。我想在点击时更改每个div的背景颜色但没有任何效果......为什么会这样?

这是我的代码

<body>
    <div id="wrapper">
        <header>
        </header>

        <div id="buttonscontainer">
            <button class="button" id="add">+</button>  
            <button class="button" id="remove">-</button>   
        </div>

        <main id="main">
        </main>
    </div>      
</body>

脚本:

window.onload=function(){
    for(var i=0;i<6;i++){
            var rectangle = '<div class="rect"></div>';
            document.getElementById("main").innerHTML += rectangle;
        }
    document.getElementById("add").onclick = addRect;
    document.getElementById("remove").onclick = removeRect;
    }

/*defines the behaviour of the addRect onclick*/
 function addRect(){
     var rectangle = '<div class="rect"></div>';
     document.getElementById("main").innerHTML += rectangle;
 }

 /*defines the behaviour of the removeRect onclick*/
 function removeRect(){
     var rectangle = '<div class="rect"></div>';
     document.getElementById("main").lastChild.remove();
 }

2 个答案:

答案 0 :(得分:1)

鉴于你已经拥有的,你可以这样做:

window.onload=function(){
    for(var i=0;i<6;i++){
        //just make use of addRect here, no need to duplicate code
        addRect();
    }
}

//Update addRect to add elements in a more DOM like manner,
//so we don't clear previously bound events
function addRect(){
    var rectangle = document.createElement('div');
    rectangle.className = 'rect';
    document.getElementById("main").appendChild(rectangle);
    document.getElementById("main").lastChild.onclick = changeColour;
}

function changeColour() {
    this.style.backgroundColor = '#ff0000';
}

Demo

答案 1 :(得分:0)

代码中没有css。你想怎么改变bg的颜色? 代码有效,你正在添加零高度的rects。 您应该使用chrome dev工具来查看更改..