user3011565
user3011565

Reputation: 13

click event does not fire on newly created li tags

With the following code:

<!DOCTYPE html>
<html>
<head>
<title>test list</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<style>
li{
display:inline;
}
</style>
<body>
<input type="hidden" value="4" id="value">

<ol></ol>

<button id="btn2">increase</button>
<button id="btn1">show</button>
<p></p>
</body>
<script>
$("li").click(function(){
    $(this).nextAll().css({"color":"red"});;
});

$("#btn2").click(function(){
    var text="<li> -> kkk</li>"; 
    $("ol").append(text);
});

$("#btn1").click(function(){
    $("p").text($("li").length);
});
</script>
</html>

any newly created "li" tags that appear after clicking "increase" button, do not trigger handlers bound to the click event.

$("li").click(function(){
    $(this).nextAll().css({"color":"red"});;
});

Can you please tell me the reason why it's not work. And is it possible to make it work? If yes, How? Thank you very much.

Upvotes: 1

Views: 1634

Answers (4)

user3011650
user3011650

Reputation: 1

May help to put your script library before the closing body tag ...

    increase show

    ... see here: fiddle link

    $(function() {  
    $("#btn2").click(function(){  
        var text= " --> ";  
        $('ol').append('<li>'+text+'</li>');  
        $('ol li:not(":first")').css('color','red');  
    });  
    
    $("#btn1").click(function(){  
        $("p").text($("li").length);  
    });     
    });  
    

    Upvotes: 0

    Adrian C.
    Adrian C.

    Reputation: 19

    try this code:

       $(document).on('click', 'li', function(){
    
            $(this).nextAll().css({"color":"red"});;
       });
    

    Upvotes: 0

    Nitesh Kumar Anand
    Nitesh Kumar Anand

    Reputation: 621

    From jQuery documentation: "Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next."

    Upvotes: 1

    Ankit Tyagi
    Ankit Tyagi

    Reputation: 2375

    Try like this : As your 'li' are generating dynamically ( For further reading )

    $("body").on('click','li',function(){
        $(this).nextAll().css({"color":"red"});;
    });
    

    Upvotes: 5

    Related Questions