Assign event click to button added to DOM with jQuery

Asked

Viewed 3,388 times

0

By clicking a button I make a string appear, but this string has a button (let’s call it a 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 that calls the Jquery function, as shown 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 tried without using jquery, by onclick() even and in this case the console said that the function was not set.

Below I put the complete code, it is half crazy, I think they will not understand. The ajax is there incomplete, because I will finish. What really matters is this 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>Exemplo 1</h1>
  <!--<input type="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>

  • You can post the entire code?

  • I did, Anderson

1 answer

5


First, the attribute of id HTML defines unique elements in the document, so create multiple buttons with id="negacao" makes no 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 which will have this event. Elements added to the DOM later will not have the same effect. To do this, you need to add the event to the element manually. First, see the example showing how it doesn’t 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>

<div id="div1">
  <button type="button" class="negacao">Pressione-me!</button>
</div>

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

To correct:

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>

<div id="div1">
  <button type="button" class="negacao">Pressione-me!</button>
</div>

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

Thus manually assigning the event click, with the function do_something 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 its necessity according to its problem in view that it was not possible to reproduce it completely here.

  • Thank you, your reply helped a lot. It went all right here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.