2017-02-27 93 views
-1

我有一個div,當用戶點擊它時,20個嵌套的div每個裏面的另一個應附加。當任何這些div被點擊它應該消失,而不會影響其子。 Nested div structure.When, for example, the 10th(highlighted with red) is clicked it should disappear嵌套的div可以點擊刪除

如果問題是微不足道的,我很抱歉打擾你。謝謝。

代碼:

function run(e) { 
 
    var div = document.createElement("div"); 
 
    div.setAttribute('class', 'Delete'); 
 
    div.addEventListener("click", run); 
 
    e.target.appendChild(div); 
 
    this.removeEventListener("click", run); 
 
    e.stopPropagation() 
 

 
} 
 
function removeChildDiv(e) 
 
{ 
 
    if(e.target.className === 'Delete') 
 
    { 
 
     e.target.parentNode.removeChild(e.target); 
 
    } 
 
    document.getElementById("1").addEventListener("click", run); 
 
} 
 

 
document.getElementById("1").addEventListener("click", run); 
 
document.getElementById("1").addEventListener("click", removeChildDiv);
html, body { 
 
    height: 100%; 
 
    width: 100%; 
 
} 
 

 
div { 
 
    border: 1px solid black; 
 
    width: 90%; 
 
    height: 90%; 
 
    background-color:green; 
 
}
<div id="1"></div>

+0

你有什麼迄今所做?你能告訴我們一些代碼嗎? – putvande

+0

@ putvande https://jsfiddle.net/narekeranyan/v8n1wvu0/13/這是一個div和點擊另一個div創建,但當再次點擊它的孩子也被刪除 – Alex

+0

@ putvande所以這裏是代碼...什麼下一個? – Alex

回答

0

https://jsbin.com/mekumaralo/edit?html,css,js,output

var parentD = document.getElementById("1"); 
window.onload = function() { 
    for (var i = 0; i < 10; i++) { 
    var div = document.createElement("div"); 
    div.textContent = "div " + i; 
    parentD.appendChild(div); 
    parentD = div; 
    } 
} 


function removeChildDiv(event) { 

//if the parent is the body, we know this is the root Div element 
//alternatively you could compare the node to the root and 
//store the root as a variable 
    if(event.target.parentNode == document.body) { 

//if there is a child add the event listener to that child 
//before removing the root div 
    if (event.target.firstElementChild) { 
     event.target.firstElementChild.addEventListener("click", removeChildDiv); 
    } 
    } 

    // changed to firstElementChild 
    // firstChild will pick up text nodes, firstElementChild will not. 
    while (event.target.firstElementChild) { 
    event.target.parentNode.insertBefore(event.target.firstElementChild, event.target); 
    } 


    event.target.parentNode.removeChild(event.target); 
} 


parentD.addEventListener("click", removeChildDiv);