Access dynamically created items using jQuery?

后端 未结 6 1534
说谎
说谎 2020-12-19 13:13

I have a page where some html is being dynamically added to the page.

This is the html and javascript that is created:

6条回答
  •  忘掉有多难
    2020-12-19 14:06

    You have to bind on() (or the events defined within the on() method, to an element that exists in the DOM at the point at which the jQuery was run. Usually this is on $(document).ready() or similar.

    Bind to the closest element in which the $('#btn') element will be appended that exists in the DOM on page-load/DOM ready.

    Assuming that you're loading the $('#btn') into the #container div (for example), to give:

    
    

    Then use:

    $('#container').on('click', '#btn', function(){
        alert('Button clicked!');
    });
    

提交回复
热议问题