- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to bind jQuery events within dynamic content returned via Ajax?
To bind jQuery events within dynamic content, use event delegation. You can try to run the following code to learn how to bind jQuery events within dynamic content returned via Ajax:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(".loadingAjax").on("click", function() { event.preventDefault(); var url = $(this).attr("href"), appendedContainer = $(".append"); $.ajax({ url: url, type : 'get', complete : function( qXHR, textStatus ) { if (textStatus === 'success') { var data = qXHR.responseText appendedContainer.hide(); appendedContainer.append("<a href='#' class='link'>Hi</a>"); appendedContainer.fadeIn(); } } }); }); $(document).on("click", '.link', function(event) { alert("Link clicked!"); }); }); </script> <style type="text/css"> a.test { font-weight: bold; } body { font-family: sans-serif;} </style> </head> <body> <a class="loadingAjax" href="https://www.qries.com"> Click to load Ajax</a> <div class="append"></div> </body> </html>
Advertisements