The click event does not fire when an element is inserted into dom from the js variable

Can someone explain to me why the click event does not fire when an element is inserted into dom from a variable

Consider

HTML

<div id="disp"></div>
<input type="button" value="clickme" id="cme"/>

JQuery

$("#cme").click(function(){
    var inside = '<input type="button" value="clickme again" id="sme"/>';
    $("#disp").html(inside);
});

$("#sme").click(function(){
    alert("clicked me");  
});

When you click clickmeto dispadd a new button clickme again, and the button is pressed clickme againit does not trigger attached to it the click event. doesn't it bother me? why?

But when I tried this way, it works

$("#cme").click(function(){
    var inside = '<input type="button" value="clickme again" id="sme"/>';
    $("#disp").html(inside);
    // when i put here , it works
    $("#sme").click(function(){
        alert("clicked me");  
    });
});

I want to put it $("#sme").clickoutside. Any help is appreciated. Thanks

+4
source share
2 answers

try something like this

$("#disp").on('click', "#sme", function(){
    alert("clicked me"); 
});

Cause

click , DOM. on() jQuery

, -, . , , , , click , .

+2

.on()

$("#disp").on('click', "#sme", function(){
    //Your code
    alert("clicked me"); 
});
+2

All Articles