javascript - Making JQuery Recognise Newly Added Elements -


this question has answer here:

how make jquery treat new elements in same way original elements in html file treated? example, consider following example:

<!doctype html> <html>     <head>         <title>simple click switch</title>         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>         <script type="text/javascript">             $edit = "<div>edit</div>";             $(document).ready(function () {                 $("div").click(function () {                     $(this).after($edit);                     $edit = $(this);                     $(this).remove();                 });             });         </script>     </head>     <body>         <div>switch me</div>     </body> </html> 

i expected block of jquery allow me toggle between divs "switch me" , "edit", on clicking. however, result is, recognises original div, allowing single "toggle". newly added div not recognised jquery. div can toggled once. how solve problem?

for dynamically added elements need use event delegation register handlers

$(document).on('click', 'div', function () {                 $(this).after($edit);                 $edit = $(this);                 $(this).remove();             }); 

demo: fiddle

also read this


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -