refresh DOM after append element

前端 未结 5 1266
忘了有多久
忘了有多久 2020-12-09 16:24



        
相关标签:
5条回答
  • 2020-12-09 16:59

    You need to use event delegation for dynamically added element.

    $(document).ready(function() {
        $('#main_body').append("<h1>Hello</h1><input id=\"but\" type=\"button\">Click");
        $('#main_body').on('click', '#but', function() {
            alert( "bla bla" );
        });
    });
    

    Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future

    0 讨论(0)
  • 2020-12-09 16:59

    Use like this

    <!doctype html>
    <html>
    <head>
    <title>test</title>
    <meta charset="UTF-8">
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    
        $(document).ready(function () {
            $('#main_body').append("<h1>Hello</h1><input id=\"but\" type=\"button\">Click");
            $(document).on("click", "#but", function () {
                alert("bla bla");
            });
        });
    
    </script>
    </head>
    <body id="main_body">
    </body>
    

    you should use event delegation for that

    It helps you to attach handlers for the dynamically created elements

    0 讨论(0)
  • 2020-12-09 17:01
    $('#main_body).append("something").ready(() => {
      $('#but').click(() => {
      }) 
    });
    
    0 讨论(0)
  • 2020-12-09 17:03

    For dynamically added elements you need event delegation, use the other version on jQuery on(), you can delegate event to static parent of the dynamically added elements. In your case you can use #main_body

    $('#main_body').on( "click", "#but", function() {
        alert( "bla bla" );
    });    
    

    Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery Docs

    Your code works here as it is because you are adding the dynamically element before binding the event but using event delegation will free you from the sequence you use to add the dynamic elements.

    0 讨论(0)
  • 2020-12-09 17:15

    You code should work

    Fiddle Demo

    $(document).ready(function () {
        $('#main_body').append("<h1>Hello</h1><input id=\"but\" type=\"button\">Click");
        $("#but").on("click", function () { //element is in DOM now as it added in previous statement
            alert("bla bla");
        });
    });
    
    0 讨论(0)
提交回复
热议问题