Select class from load

0

I have a page that loads by load from jQuery as shown below:

<div id="result"></div>
<script>
  $('#result').load('listar.php');
</script>

On this page listar.php I have a list of data coming from the database as follows:

<tr>
  <td><?php echo $linha->nome; ?></td>
  <td>
    <button class="ident" value="<?php echo $linha->id; ?>">Mostrar ID</button>
  </td>
</tr>

The problem is that I can not select this class ident from <button> jQuery to get the id .

I wanted to at least do this:

$('.ident').click(function() {
  alert($(this).val());
});

How to solve this problem? what am I doing wrong?

    
asked by anonymous 09.09.2017 / 04:25

2 answers

1

First of all, I will not research sources to support what I will say.

First of all:

I wanted to at least do this:

$('.ident').click(function() {
  alert($(this).val());
});

This would solve:

$('body').on("click", ".ident", function() {
  alert($(this).val());
});

How to solve this problem?

The "base selector" for the event, should already be loaded on the screen the moment you add the listener, so just make an event bind to an element that is already on the screen and use the function parameters to do a sub-selection. (better explained below)

What am I doing wrong?

You are adding a listener to an element that is not present in the DOM at the time of execution.

Explanations:

When you add an event via JavaScript, you are assigning an action to a particular element. If a new element, even with the same selector, is inserted into the DOM after executing this code, it will not be listening for that event.

In this case, you added an event to the .ident class, but only elements with the ident class that were already in the DOM at the time the code was executed would be bound to it.

Why use $('body').on('click', '.ident', function(){}); resolves?

In this case, the click event is being added to the body element, which is already in the DOM at run time, which jQuery is doing behind in this case, is basically: "after clicking inside the body element, checks to see if it was in the element that has a ident class. In this way, the event is bound to the body, not to the element with the ident class, jQuery only confirms that the clicked element has the desired class, it does not keep any event bound to the class or other element (besides the body) in specific.

    
09.09.2017 / 06:10
1

Use event .on() :

$("body").on("click",".ident",function(){
    alert($(this).val());
});
    
09.09.2017 / 04:51