Assign event click to button added to DOM with jQuery

0

By clicking a button I make a string appear, but this string has a button (let's call button2), but button2 does not work. Why?

I click this button:

$("#button1").click(function(){
    $("#div1").append(palavra1);

  });

However, word1 has a button written, with id calling the Jquery function, like the one I showed above.

This button is displayed in # div1, but when I click it, it does not do what the function says, which in this case is an alert ("test");   I have tried using jquery, by onclick () and in this case the console said that the function was not defined.

Below I put the complete code, it's kind of crazy, I guess they will not understand. The ajax is incomplete because I'm still going to finish. What really matters is that part of the button.

$("#negacao").click(function() {
  $("#div1").append("algo");
});


$(document).ready(function() {
  $('#ajax').on('click', AJAX);

  function AJAX() {
    $.ajax({
      method: 'post',
      url: 'new2.php',
      data: {
        ncode: "asfdasf"
      },
      success: function(retorno) {
        $('#conteudo_ajax').html(retorno);

      }
    });
  }
  var palavra = $("div#algo").text();
  var reserva = palavra;
  var vseq = palavra.split("||");

  for (var i = 0; i < vseq.length; i++) {
    //alert(vseq[i]);
    var partes = vseq[i].split("|--");
    var antes = partes[0];
    var depois = partes[1];
    var contextos = depois.split(";");
    var classico = contextos[0]; // contexto classico [... ]
    var linear = contextos[1]; // contexto linear {... }
    var formula = linear.slice(2, linear.length - 2);
    var sublinear = formula.split(",");
    for (var i = 0; i < sublinear.length; i++) {
      if (sublinear[i].match(/~\D?\(\D?\D?\D?\D?\D?\D?\D?\D?\D?\D?\D?\)/ig)) {
        //alert(sublinear[i]);
        //alert(palavra.lastIndexOf(sublinear[i]));
        var chapeu = sublinear[i].indexOf("~");
        var parens = sublinear[i].indexOf("(");

        var corte1 = sublinear[i].slice(chapeu, parens);
        var corte2 = sublinear[i].slice(parens, sublinear[i].length);


        palavra1 = palavra.replace(sublinear[i], "<button type='button' class='regra' id='negacao' >" + corte1 + "</button>" + corte2);
        //alert(palavra1);
        $("#button1").click(function() {
          $("#div1").append(palavra1);

        });


      } else {
        alert("NAO TEM NEGACAO");
      }

    }



    /*for(var j = 0; j < contextos.length; j++){
     	alert(contextos[j]);
     }\ */


  }




});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><fieldset><h1>Exemplo1</h1><!--<inputtype="button" value="$.ajax()" id='ajax'><br> -->
  <div id="algo"> [C',F] ; {empty} |-- [D'] ; {~(F + ~ G)} </div>
  <br>[C'] ; G |-- [D'] ; {F + G}
  <br>[C'] ; {! F} |-- [D'] ; {~ (F & G), D}
  <br/>
  <div id='conteudo_ajax'></div><br>
</fieldset>

<div id='div1'> </div>
<br><button id='button1'> AA </button> <br>
    
asked by anonymous 03.05.2017 / 00:40

1 answer

3

First, the id attribute of HTML defines unique elements in the document, so creating multiple buttons with id="negacao" does not make sense and is semantically wrong.

Second, when you assign a function to an event, such as:

$("#negacao").click(function() {
  $("#div1").append("algo");
});

Only the element initially loaded into the DOM, whose id is equal to negacao that will have this event. Elements added to the DOM later will not have the same effect. To do this, you must add the event to the element manually. First, look at the example demonstrating how it does not work:

$(document).ready(function() {

  $(".negacao").click(function () {
    console.log("Eu funciono!");
  });
  
  $("#btn1").click(function () {
    $("#div1").append("<button type=\button\" class=\"negacao\">Pressione-me!</button>");
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="div1">
  <button type="button" class="negacao">Pressione-me!</button>
</div>

<button type="button" id="btn1">Adicionar</button>

To fix:

function do_something() {
  console.log("Eu funciono!");
}

$(document).ready(function() {

  $(".negacao").click(do_something);
  
  $("#btn1").click(function () {
    // Cria o novo botão:
    const newBtn = $("<button type=\button\" class=\"negacao\">Pressione-me!</button>");

    // Atribui o evento click a ele:
    newBtn.click(do_something);
  
    // Adiciona-o à lista de botões:
    $("#div1").append(newBtn);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="div1">
  <button type="button" class="negacao">Pressione-me!</button>
</div>

<button type="button" id="btn1">Adicionar</button>

In this way, by manually assigning the click event, with the do_something function to the new document element, the button will work perfectly.

  

In the answer I presented the basic idea of the solution, being necessary adaptations to your need according to your problem since it was not possible to reproduce it completely here.

    
03.05.2017 / 01:11