Select class from load

Asked

Viewed 48 times

0

I have a page that is loaded by function load of jQuery as an example below:

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

On this page listar.php I have a database listing 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 I can’t select this class ident of <button> for jQuery to catch the id.

I wanted to at least do that:

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

How to solve this problem? What I’m doing wrong?

2 answers

1

Use the event .on():

$("body").on("click",".ident",function(){
    alert($(this).val());
});
  • The first code does not work. Edit your answer and put only the second that works. It has the function of .delegate()which has been discontinued. When an element is added dynamically on the page, the second code works.

1


First of all, I will not search sources to substantiate what I will say.

First of all:

I wanted to at least do that:

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

That 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 at the time 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 make a sub-selection. (further explained below)

What I’m doing wrong?

You are adding a Listener to an element that is not yet 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 the execution of this code, it will not be listening to this event.

In case, you added an event to class .ident, however, only the elements with the class ident that were already in the DOM at the time of execution the code would be linked to it.

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

In this case, the click event is being added to the element body, that is already in the DOM at the time of execution, what jQuery is doing behind this case, is basically: "after clicking inside the element body, checks if it was in the element that has a class ident". In this way, the event is linked to the body, and not to the element with the class ident, jQuery just confirms that the clicked element has the desired class, it does not keep any event linked to the class or other element (other than the body) in specific.

  • 1

    Your answer is very good, thank you.

Browser other questions tagged

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