Access dynamically created items using jQuery?

后端 未结 6 1503
说谎
说谎 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:

    <div id="container">
        <div>
            <a href="#" id="btn">Button text</a>
        </div>
    </div>
    

    Then use:

    $('#container').on('click', '#btn', function(){
        alert('Button clicked!');
    });
    
    0 讨论(0)
  • 2020-12-19 14:07

    Try

    <div>
         <a id="btn">Button</a>
    </div>
     <script>
    
        $('#btn').on('click', function() {
            alert("Hello");
        });
    
    </script>
    
    0 讨论(0)
  • 2020-12-19 14:07

    The problem in your code is that you are attaching the event to the button before the button is being created.

    Correct version is:

      <div>
           <a id="btn">Button</a>
           <script type="text/javascript" language="javascript">
               $('#btn').click(function() {
                  alert("Hello");
               });
           </script>            
      </div>
    

    This should do the job.

    0 讨论(0)
  • 2020-12-19 14:10

    Use .on to wire up the event to your button. Check this SO answer:

    Event binding on dynamically created elements?

    $(document).ready(function() {
        $('body').on('click', '#btn', function() {
            alert("Hello");
        });
    })
    

    Edit: I added the document ready code, you'll want to make sure you do that.

    Fixed.

    0 讨论(0)
  • 2020-12-19 14:13

    Use the .live() function of jQuery

    0 讨论(0)
  • 2020-12-19 14:17

    you are looking for .on here which will bind the click event to dynamically added nodes.

    $("#parent_container").on("click", "#btn", function () {
        alert("hello")
    })
    

    the docs: http://api.jquery.com/on/

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