Event on element created after DOM loading

0

Next: I have a page where requests will be made. In this page, the user chooses the item and can, if wanted, add extra items to this item, for example "more cheese". When I enter this "more cheese", I create a row with two columns in the table of extra items. The first contains the description of the extra item and the second a button pto delete this item if necessary. Problem: If I enter more than one item, the event is triggered by passing the last item as parameters.

                    id = gera_id(itemExtra[0].replace(' ', '')); // Função para não existir duplicidade de ids
                var table       = document.getElementById(tabela);
                var n_rows      = document.getElementById(tabela).rows.length;
                var row         = table.insertRow(n_rows);
                row.id          = id;
                var cell1       = row.insertCell(0);
                var cell2       = row.insertCell(1);
                cell1.innerHTML = itemExtra[1];

                var deletaExtra = document.createElement("INPUT");
                deletaExtra.setAttribute("type", "button");
            /*
                deletaExtra.onclick = function (){
                    deletaItemExtra(id, tabela);
                }
            */
                var parametros = ""+id + "," + tabela+"";
                deletaExtra.addEventListener("click", function(){
                    deletaItemExtra(id, tabela);
                });

                deletaExtra.setAttribute("value", 'X');
                cell2.appendChild(deletaExtra);

If necessary, follow the link to the full page. link

    
asked by anonymous 29.07.2017 / 01:39

1 answer

1

Version with pure Javascript:

First we create this small function that will separate the classes of the element individually if it has multiple classes using .split() , then using .indexOf() will instruct you to start searching for the class name with the index of -1 , which is basically checking for something that is not yet in this group.

Has Class?

function temClasse(elem, className) {
    return elem.className.split(' ').indexOf(className) > -1;
}

Then we'll control what happens in the click event. In the first example I posted, I had clicked on the document but I corrected it now by pointing it to the parent element which is a better practice because so we are not checking clicks on the document but on the target element that is what interests us.

When a click occurs on the parent element, which in this case will be the class .container , we will check with if if this click was on the target element >) with class el-alvo or not, together with this if check we will run the temClass function to search for new indexOf() > -1 elements.

Clicked on target element?

var container = document.querySelector('.container');
container.addEventListener('click', function (e) {
    if (temClasse(e.target, 'el-alvo')) {
        alert(e.target.id);
    }
});

Recapping this part, whenever a click occurs on .container , => if / if this click was on a child element with class .el-alvo together also check if there are new elements => do something .

Example:

var container = document.querySelector('.container');

// Código abaixo não interessa. Apenas para criar novos elementos
document.getElementById('add-el').addEventListener('click', function() {
    var el = document.createElement('li');
    var id = Math.floor(Math.random() * 2000);
    el.id = id;
    el.className = 'el-alvo';
    el.innerHTML = id;
    container.appendChild(el);
});

function temClasse(elem, className) {
    return elem.className.split(' ').indexOf(className) > -1;
}
container.addEventListener('click', function (e) {
    if (temClasse(e.target, 'el-alvo')) {
        alert(e.target.id);
    }
});
.container li {
  padding: 5px;
  background-color: #fff;
  color: #000;
}

.container li:nth-child(odd) {
  background-color: #eee;
}
<ul class="container">
    <li id="primeiro" class="el-alvo">primeiro</li>
    <li id="segundo" class="el-alvo">segundo</li>
    <li id="terceiro" class="el-alvo">terceiro</li>
</ul>
<button id="add-el" type="button">
Add li
</button>
  

More about split() here: w3schools - split () Method
  More about indexOf() here: w3schools - indexOf () Method

JQuery version would look something like:

With jQuery it would be something shorter as in this example below:

// Código abaixo não interessa. Apenas para criar novos elementos
document.getElementById('add-el').addEventListener('click', function() {
    var el = document.createElement('li');
    el.className = "el-alvo";
    var id = Math.floor(Math.random() * 2000);
    el.id = id;
    el.innerHTML = id;
    document.querySelector('.container').appendChild(el);
});

// com jQuery
$('.container').on('click', '.el-alvo', function(e) {
    alert(e.target.id);
});
.container li {
  padding: 5px;
  background-color: #fff;
  color: #000;
}

.container li:nth-child(odd) {
  background-color: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><ulclass="container">
    <li id="first" class="el-alvo">first</li>
    <li id="second" class="el-alvo">second</li>
    <li id="third" class="el-alvo">third</li>
</ul>
<button id="add-el" type="button">
Add li
</button>
    
29.07.2017 / 04:38