Jquey does not work with inserted elements using . html()

Asked

Viewed 32 times

1

Good night people, then.. I have an ajax code that takes a loop inside a php file and then inserts the result inside an html page. So far, everything works. The problem is when I want to manipulate some class that was inserted using . jquery’s html() that it just doesn’t do anything. As if that class didn’t exist.

Php code:

if ($stmt->num_rows != 0) {

while($stmt->fetch()) {

  $info = substr($info, 0, 100);

  echo '<div>
      <a class="uk-link-reset" href="detalhes?id='.$id.'">
      <div class="uk-card uk-card-default uk-card-hover">
        <div class="uk-card-media-top">
          <img class="imagem_produto" src="'.$imagem.'">
        </div>
        <div class="uk-card-body">
          <h6>'.$nome_categoria.'</h6>
          <h2 class="uk-card-title uk-margin-small-top">'.$nome.'</h2>
          <p class="uk-text-justify">'.$info.'...</p>
          <div class="uk-grid-collapse uk-child-width-expand@s uk-text-center" uk-grid>
            <div>
              <div class="uk-background-muted uk-padding-small">R$ '.$valor_novo.'</div>
            </div>
          </div>
        </div>
      </div>
      </a>
  </div>';

}

}

Ajax code:

$.ajax({
type: 'POST',
dataType: 'html',
url: 'processos/produtos.php',
success: function(data) {
  $(".produtos").html(data);
}
});

So if I do, a simple:

$(".uk-text-justify").click(function(){alert('algo')});

Doesn’t work.

  • If the $(".uk-text-justify").click(function(){alert('algo')}); is executed before the ajax then the elements coming from ajax will not have the click Handler. This is a delegation problem, and already have several questions here from that: problem-with-event-onload , I can’t-can’t-remove-them-fields-I just-put , among others

  • But he runs after.

  • When I said executed, I refer specifically to assigning the click Handler => define which code for the click and not specifically the act of clicking on the element.

  • Exactly. It runs after the element is defined on the page.

1 answer

0


Turn this:

$(".uk-text-justify").click(function(){alert('algo')});

Therein:

$(document).on("click", ".uk-text-justify", function(){ 
    alert('algo');
});
  • Perfect. It helped a lot.

Browser other questions tagged

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