-1

jQuery functions not affect on appeneded elements after ajax

I know there are two ways for thats

but evey way not the best

frist when I appened element I append jquery functions again that mean evey append element I will appened the functions may be that is not best

second use .live("click" instead of .on("click"

but I know .live works with old jQuery version

What is the best way to jquery functions work with elements will appended in the future

khalid seleem
  • 117
  • 1
  • 8
  • Please include the relevant code that shows your ajax and append. – Carsten Løvbo Andersen Oct 27 '22 at 07:11
  • *"second use .live("click" instead of .on("click" but I know .live works with old jQuery version... What is the best way to jquery functions work with elements will appended in the future"* If you look at the [`live` documentation](https://api.jquery.com/live/), it'll tell you -- use the delegating form of [`on`](https://api.jquery.com/on/) instead. – T.J. Crowder Oct 27 '22 at 07:19

1 Answers1

-1

You can delegate the event handling to a container to where items are appended. The full details of this technique are outlined in the jQuery documentation: Understanding Event Delegation

Instead of:

// Attach a directly bound event handler
$( "#list a" ).on( "click", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
});

you'd do

// Attach a delegated event handler
$( "#list" ).on( "click", "a", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
});
Chase
  • 3,028
  • 14
  • 15