Events triggered by dynamically generated element are not captured by event handler

后端 未结 5 2023
失恋的感觉
失恋的感觉 2020-11-21 05:46

I have a

with id=\"modal\" generated dynamically with the jQuery load() method:

$(\'#modal\').load(\'handl         


        
相关标签:
5条回答
  • 2020-11-21 06:34

    When you dynamically change the DOM, jQuery won't attach event handlers to them. You need to use on() and delegated events

    For your input items, you'll need something like:

    $("<parentSelector>").on("keyup", "input", function() { 
        handler = $(this).val();
        name = $(this).attr('name');
    })
    

    Where the parentSelector is something higher in the DOM than the input element, and an element that exists at page load, maybe the form ID or something.

    0 讨论(0)
  • 2020-11-21 06:39

    Function binds are made ​​in page load. To work on elements created dynamically using the function live (). Example:

    $ ("p"). live ("click", function () {
        // Your function
    });
    
    0 讨论(0)
  • 2020-11-21 06:43

    If you need to capture changes for all of the form elements, particularly select boxes, I know they are not mentioned here, but it is helpful to know, use the following code:

    $(document).on('change', ':input', function () {
       alert('value of ' + $(this).attr('name') + ' changed')
    });
    

    This should cover all input, textarea, select, checkbox, radio, etc.

    0 讨论(0)
  • 2020-11-21 06:46

    This is happening because you're adding the input element after you wired up the event. Try .on:

    $('body').on('keyup', 'input', function() {
        handler = $(this).val();
        name = $(this).attr('name');
    });
    

    Using .on will make sure the keyup event is wired up to inputs that are on the page originally, as well as any that are added later dynamically.

    0 讨论(0)
  • 2020-11-21 06:51

    You need to delegate the event to the closest static ancestor element within the page (see also "Understanding Event Delegation"). This simply means, the element where you bind your event handler must already exist at the time the handler is bound, so for dynamically generated elements you must allow the event to bubble up and handle it further up.

    The jQuery .on method is the way to do this (or .delegate for older versions of jQuery.)

    // If version 1.7 or above
    
    $('#modal').on('keyup', 'input', function() {
        handler = $(this).val();
        name = $(this).attr('name');
    });
    

    Or in older versions

    // If version 1.6 or below
    
    // note the selector and event are in a different order than above
    $('#modal').delegate('input', 'keyup', function()
    {
        handler = $(this).val();
        name = $(this).attr('name');
    });
    
    0 讨论(0)
提交回复
热议问题