Responding to click event of element added to document after page load

前端 未结 6 1617
无人及你
无人及你 2020-12-12 00:54

I am writing a page which uses a lot of in situ editing and updating using jQuery for AJAX.

I have come accross a problem which can best be summarized by the workfl

相关标签:
6条回答
  • 2020-12-12 01:22

    Live events is what you're looking for.

    0 讨论(0)
  • 2020-12-12 01:28

    live is deprecated, use .on() like such:

    $('#table tbody').on('click', 'tr', function(e){
        var row = $(this).find('td:first').text();
        alert('You clicked ' + row);
    });
    
    0 讨论(0)
  • 2020-12-12 01:30

    you can use live() that binds a function to all elements matching your selection, even those created in the future: http://api.jquery.com/live/

    0 讨论(0)
  • 2020-12-12 01:36

    Use a live handler. deprecated since some time, check the second part of my answer for better solutions!

    $('img#inserted_form_btn').live('click', function() {
        // Your click() code
    });
    

    Assuming the image is a child of some element that already exists when binding the event, you can use a delegate instead:

    $('#parent-element').on('click', '#inserted_form_btn', function() {
        // Your click() code
    });
    

    If you do not have jQuery 1.7+:

    $('#parent-element').delegate('#inserted_form_btn', 'click', function() {
        // Your click() code
    });
    

    In any case, you can use a delegate and use $(document) instead of $('#parent-element') if there is no suitable parent element.

    0 讨论(0)
  • 2020-12-12 01:39

    Look at the 1.4.2 .delegate()

    The documentation is here:Delegate

    0 讨论(0)
  • 2020-12-12 01:47

    You need to either assign the click even as a post process event on the initial AJAX call, i.e.

    $.ajax({ url: "test.html", context: document.body, success: function(){
        $('img#inserted_form_btn').click(function(){
            $.ajax({'type: 'POST', 'url': 'www.example.com', function($data){
                $(data.id).html($data.frm);
            }), 'dataType': 'json'}
        });
    }});
    

    or use the .live method to ensure the event is reassigned when the dom element is created.

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