Home  >  Q&A  >  body text

Event binding on dynamically created elements?

<p>I have some code where I loop through all the select boxes on the page and bind the <code>.hover</code> event to them to resize their width on <code> the mouse on/ Close </code>. </p> <p>This happens when the page is ready and working properly. </p> <p>The problem I'm having is that any select boxes added via Ajax or DOM after the initial loop don't have events bound to them. </p> <p>I've found this plugin (jQuery Live Query Plugin), but before I use the plugin to add another 5k to my page, I wanted to see if anyone knows how to do it, either directly using jQuery Or through other options. </p>
P粉440453689P粉440453689444 days ago435

reply all(2)I'll reply

  • P粉930534280
  • P粉547170972

    P粉5471709722023-08-24 11:57:21

    Starting with jQuery 1.7, you should use jQuery.fn.on with the selector parameter populated:

    $(staticAncestors).on(eventName, dynamicChild, function() {});

    illustrate:

    This is called event delegation and it works as follows. This event is attached to the static parent (staticAncestors) of the element that should be handled. This jQuery handler is fired every time an event is fired on this element or one of its descendant elements. The handler then checks if the element that triggered the event matches your selector (dynamicChild). When there is a match, your custom handler function is executed.


    Until then, the recommended method is to use live()< /代码>:

    $(selector).live( eventName, function(){} );

    However, live() was deprecated in 1.7, replaced by on(), and removed entirely in 1.9. live() Signature:

    $(selector).live( eventName, function(){} );

    ...can be replaced with the following on() signature:

    $(document).on( eventName, selector, function(){} );

    For example, if your page dynamically creates an element with the class name dosomething, you can bind that event to an already existing parent (which is the core of the event ) The problem here is that you need something existing to bind to, rather than binding to dynamic content) this can be (and the easiest option) is document. But keep in mind that document may not be the most efficient option.

    $(document).on('mouseover mouseout', '.dosomething', function(){
        // what you want to happen when mouseover and mouseout 
        // occurs on elements that match '.dosomething'
    });

    Any parent that exists when the event is bound will do. For example

    $('.buttons').on('click', 'button', function(){
        // do something here
    });

    Applies to

    <div class="buttons">
        <!-- <button>s that are generated dynamically and added here -->
    </div>

    reply
    0
  • Cancelreply