Solucio botons celestials

De wikiserver
Dreceres ràpides: navegació, cerca

HTML:

<html>
    <head>
        <script type="text/javascript" src="bceles.js"></script>
    </head>
    <body></body>
    
</html>

Javascript:

window.listId = [];
window.numButton = -1;

function init(){
    createButton("func0");
    createButton("func1");
}

function func0(){
    //angelet
    var maxb = Math.floor(Math.random()*10);
    for(i=0;i<maxb;i++){
        createButton();
    }
        
}


function func1(){
    //diablet
    var maxelements = Math.min(20,window.listId.length);
    var numbuttondeleted = Math.floor(Math.random()*maxelements);
    for(i=0;i<numbuttondeleted;i++){
        deleteNode();
    }
    
    function deleteNode(){
        var index =  Math.floor(Math.random()*window.listId.length);
        var delboton = document.getElementById(window.listId[index]+"");
        delboton.parentNode.removeChild(delboton);
        window.listId.splice(index,1);
    }
    
}

function createButton(func){
    var div = document.createElement("span");
    div.setAttribute("id", window.numButton)
    var b = document.createElement("button"); 
    func = (func)? func : "func"+Math.floor(Math.random()*2);
    b.onclick = function(){eval(func +"()");};
    var t = document.createTextNode("b" + window.numButton);
    b.appendChild(t);
    div.appendChild(b);
    document.body.appendChild(div);  
    window.listId.push(window.numButton);
    window.numButton++;
}

window.onload = function(){init();};


opció 2

var i = 1;
document.getElementById('creator').addEventListener('click',function(){
  var div = document.createElement('div');
  var text = document.createTextNode('New Div ' + i);
  div.appendChild(text);
  document.body.appendChild(div);
  i++;
});
document.addEventListener('click',function(e){
    // Fixed
    if(e.target.tagName.toLowerCase() === 'div'){
        console.log(e.target);
    }
 })
<div>
  Div actual
</div>
<button id='creator'>Crear</button>