Binding dynamically created elements in jQuery

后端 未结 5 1709
伪装坚强ぢ
伪装坚强ぢ 2020-12-11 09:15

The following code is fairly self explanatory, but I am running in to an issue binding the click event to an element that has been created.

You can see at line 25 I

相关标签:
5条回答
  • 2020-12-11 09:56

    The click event to the overlay is binded before the element exists. You need to use live binding to retain the binding – otherwise you'd have to do the bind every time you create the element. Just change your function to use live() like this:

    $('#overlay').live('click', function () {
        $('#overlay').fadeOut(1000);
        $('.modal').fadeOut(200);
    });
    

    The click event for .modal .close works as it is already defined in the DOM when the event is bound.

    Normal event binding only considers the elements that currently exist in the DOM while events bound with live() work also on all future elements that match the selector.

    0 讨论(0)
  • 2020-12-11 10:01

    If you're creating #overlay programmatically, you need to bind it with $.live();

    $('#overlay').live("click", function () {
      $('#overlay').fadeOut(1000);
      $('.modal').fadeOut(200);
    });
    

    This method of binding binds to all present, and future elements that match the provided selector.

    0 讨论(0)
  • 2020-12-11 10:01

    Keep in mind that your code will create a new overlay each time the a[name=modal] link is clicked..

    Either remove the overlay element from the DOM when you are done with it .. or create it outside of the click, and just show/hide it on the click event ..

    You specific problem is that you bind the click event to the overlay before it is ever created (since you will created after you click the link ..)

    0 讨论(0)
  • 2020-12-11 10:18

    Using the .live() method it will work with any elements you add to the DOM after its loaded.

    // Overlay click = trigger out
    $('#overlay').live('click', function () {
        $('#overlay').fadeOut(1000);
        $('.modal').fadeOut(200);
    });
    

    Another way to do it would be to bind it to click when it is added (inside the click handler for $('a[name=modal]').

    You should probably also change $('#overlay').fadeOut() to $(this).fadeOut().

    0 讨论(0)
  • 2020-12-11 10:19
     // Overlay click = trigger out
        $('#overlay').click(function () {
            $('#overlay').fadeOut(1000);
            $('.modal').fadeOut(200);
        });
    

    is triggered on page load, when the #overlay element doesn't exist. If you move this piece of code inside the $('a[name=modal]').click(function(e) { part, but after the $('body').append('<div id="overlay"></div>'); part, it should work.

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