variable with jquery html content

0

Why does not this work?

I have a variable with a structure html that when I click on a button I print it on a label p and then the button that is in that variable add a function click but doing this does not work .

The same happens when I do it with ajax that for example if I do the same with ajax I have to add again the script in the ajax so that I can to operate the funtion, to what is this due?

NOTE: css styles if taken by the variable with the content html but not the script

Here is an example of what I'm trying to do

$(document).ready(function(){
    var contenido='
     <div>
       <button id="pinchar2"> pinchar</button>
     </div>
    ';

    $('#pinchar').click(function() {
        alert("pinchado")
        $('p').html(contenido);
    });

    //luego al tratar de agregar la misma funcion a la variable me falla
    $("#pinchar2").click(function(){
        alert("pinchado")
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

<div>
    <button id="pinchar">check</button>
</div>
   
<p></p>
    
asked by andy gibbs 30.09.2018 в 03:37
source

1 answer

2

What happens is that when you look for the button # click2 to assign the click event, it has not yet been added to the sun, since it is added until you click on the #pinchar button.

What you have to do is assign the click event until after you have inserted it in the sun:

$(document).ready(function(){
    var contenido='
     <div>
       <button id="pinchar2"> pinchar</button>
     </div>
    ';

    $('#pinchar').click(function() {
        alert("pinchado")
        var p = $('p');
        p.html(contenido);

        p.find("#pinchar2").click(function(){
            alert("pinchado")
        });

    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

<div>
    <button id="pinchar">check</button>
</div>
   
<p></p>

Your code what it does is run at the moment of loading the page (ready event).

The first thing he does is look for the #pinchar element and assign a function to execute when he clicks.

Then, look for the element #pick2 to assign a function to execute when you click, but you can not find it because that button does not exist yet, since it is created until you click on the #pinchar button. When you do not find the button # click2, you can not assign the click event.

    
answered by 30.09.2018 / 03:55
source