Assign function to dynamically generated button [duplicate]

0

Personally my problem is a bit difficult for me to explain. I have these buttons which are added every time when the "+" is clicked and when you click any of these button they remove the div pai% ( .list-group-item ).

The question is that I can only assign this function to these buttons directly in the html element ( onclick="removeField("+amntFileds+")" ) but I wanted something like:

document.querySelector(".remove-button").onclick=function(){...}

Unfortunately I can not do this because the buttons are added dynamically, and before adding them, they still do not exist by returning the selector error that does not find it. I'm trying to use this code in an extension to Chrome , and can not use inline code ...

  

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, the hash ('sha256 -...'), or a nonce ('nonce -...') is required to enable inline execution.

JS:

var amntFileds = 1;
var superObj = document.querySelector(".list-group");
var btnAdd = document.querySelector(".add-button");

btnAdd.onclick = function(){
   Element.prototype.setAttributes = function(attrs){
      for (var index in attrs){
         if ((index == 'styles' || index == 'style') && typeof attrs[index] == 'object'){
            for (var prop in attrs[index]){
               this.style[prop] = attrs[index][prop];
            }
         }else if (index == 'html'){
            this.innerHTML = attrs[index]
         }else{
            this.setAttribute(index, attrs[index]);
         }
      }
   };

   //Criando o elementos;
   var subObj = document.createElement("a");
   var inputRemove = document.createElement("button");

   //----------------Setando atributos dinamicamente-----------------\
   //Definindo atributos ao subObj(div list-group-item):
   subObj.setAttributes({
      "id" : "sub-field"+amntFileds,
      "class" : "list-group-item"
   });

   //Definindo atributos ao inputRemove(Botão de exclusão de comandos)
   inputRemove.setAttributes({
      "type" : "button",
      "class" : "remove-button",
      "html" : "✘",
      //"onclick" : "removeField("+amntFileds+")"
   });
   //-----------------------------------------------------------------\

   //Inserindo o elementos no subObj(list-group-item):
   subObj.appendChild(inputRemove);
   superObj.appendChild(subObj);
   amntFileds++;
}

function removeField(id){

   //Recebendo id de campo clicado
   var subObj = document.querySelector("#sub-field"+id); 

   //Removendo o DIV com id específico do nó-pai:
   var removed = superObj.removeChild(subObj);        

   //Decrementando campo adicionado em 1;
   amntFileds--;
   console.log("Campo "+amntFileds+" removido!");
}

HTML:

<div class="list-group">
</div>
<br><button type="button" class="add-button">&#10010;</button><br>
<script type="text/javascript" src="action.js"></script>
    
asked by anonymous 23.12.2017 / 04:03

1 answer

0

The easiest way to work with events on dynamically created elements is by using jQuery see:

$('body').on('click', '.uma-classe-qualquer', function(evt) {
    // aqui é possível pegar qualquer informação do elemento (id, data, etc...)
    alert($(this).attr('id'))
})

If the jQuery usage is not feasible in your project, the way to do this is to use addEventListener in the elements that you dynamically add example:

let inputRemove = document.createElement("button")
// adicione um "ouvinte"
inputRemove.addEventListener('click', function(evt) {
    // por exemplo para pegar o id:
    alert(this.id)
}, false)

Note that you can specify a function for reference instead of declaring one:

// awesome function
function coolFunc(evt) {
    alert(this.id)
}
// handler
inputRemove.addEventListener('click', coolFunc, false)
    
23.12.2017 / 05:32