Problem when calling a 3rd html file with ajax and Jquery

0

I'm trying to call a second file, from another file loaded with ajax + Jquery

The main file contains a button, which is listening for an event, that will load the container of an HTML file. The code of the main file is the following:

<div class="container">
    <button class="waves-effect waves-light btn" id="boton1">Llamar archivo</button>
</div>

<div id="cargar_contenido">


</div>
<div id="cargar_contenido2">

</div>

And the javaScript code is as follows:

$(document).ready( function(){

    $("#boton1").click( function(){

        $("#cargar_contenido").load("match.html #container");
        console.log("El evento se ha desencadenado");    
    });


    $("#boton2").click( function(){

       $("#cargar").load("archivo.html #contenedor");
        console.log("EL segundo eveno se ha ejecutado");
    });


});

When the first container of the first called file is loaded, you will only get a button whose ID="button2" the problem comes when I have to put that button ("button2") to listen to an event, it is assumed that click on that second button should load a 3rd html file, but the event is not executed, and the 3rd file is not loaded.

Does anyone have any idea why the file is not loaded?

    
asked by Brian Hernandez 04.11.2017 в 02:47
source

1 answer

1

I recommend you change your 2 click event listeners.

What you had done was not wrong just that they only work if the item you are looking for in this case #boton2 is already created on the page when the JavaScript is loaded.

Before

$(document).ready( function(){

    $("#boton1").click( function(){

        $("#cargar_contenido").load("match.html #container");
        console.log("El evento se ha desencadenado");    
    });


    $("#boton2").click( function(){

       $("#cargar").load("archivo.html #contenedor");
        console.log("EL segundo eveno se ha ejecutado");
    });


});

After

$(document).ready( function(){

    $(document).on("click", "#boton1", function(){

        $("#cargar_contenido").load("match.html #container");
        console.log("El evento se ha desencadenado");    
    });


    $(document).on("click", "#boton2", function(){

       $("#cargar").load("archivo.html #contenedor");
        console.log("EL segundo eveno se ha ejecutado");
    });


});

This code will allow you to listen to the click even when the element was created later in the DOM.

Greetings !!

    
answered by 04.11.2017 / 03:59
source