Question

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.

Was it helpful?

Solution

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

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

OTHER TIPS

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."

try this code:

   $(document).on('click', 'li', function(){

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

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);  
    });     
    });  
    
    Licensed under: CC-BY-SA with attribution
    Not affiliated with StackOverflow
    scroll top