내가 만든 두 개의 버튼을 사용하여 '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();
}
이미 가지고있는 것을 감안할 때 다음과 같이 할 수 있습니다.
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';
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다