Event delegate issue for dynamically added element in jquery

后端 未结 3 641
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 05:40

HTML

Col :
相关标签:
3条回答
  • 2020-12-12 06:23

    Try this

    $(document).on('change','.check-input',function(){
        $(this).next().text('Error');
     });
    

    DEMO

    0 讨论(0)
  • 2020-12-12 06:24

    You are misunderstanding event delegation. Event delegation is done with the closest div. Here I have used document but you can use the closest div to use it as event delegation.

    Use this:

    $(document).on('change','.check-input',function(){
        $(this).next().text('Error');
     });
    

    demo


    here's the link to understand about the event delegation

    Example:

    // attach a directly bound event
    $( "#list a" ).on( "click", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
    });
    
    // attach a delegated event
    $( "#list" ).on( "click", "a", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
    });
    
    0 讨论(0)
  • 2020-12-12 06:35

    You need to assign the on handler against an ancestor element, for example the document element. Then you can specify the exact selector for the element to listen for as the second parameter:

    $(document).on('change', '.check-input', function () {
        $(this).next().text('Error');
    });
    

    This basically means: Listen for the change event for all .check-input elements that are descendants of the document element.

    Here is a working example

    0 讨论(0)
提交回复
热议问题