jquery - How to setup click events on results returned via ajax? -


i returning set of links database via ajax, so:

function search_friends() {     = $('input.search_term').val();     $.ajax({         type: "post",         url: 'lib/search.php',         data: {who:who},         success: function(data) {             $('.search_results').html(data);         }         // datatype: 'json'     });     return false; } 

that return like:

<div class="search_results">     <p><b>results:</b></p>     user1 <a href="add_friend.php?pid=3" class="3">add friend</a>     <br>     user2 <a href="add_friend.php?pid=4" class="4">add friend</a><br><hr> </div> 

but page loads (before search done), have like:

$('.search_results a').click(function() {     alert('code'); }); 

but doesn't work because .search_results div returned via ajax.

how solve problem?

you trying bind event elements not exists @ time of binding. need use on bind click event event delegation.

$(document).on('click','.search_results a', function() {     alert('code'); }); 

delegated events

delegated events have advantage can process events descendant elements added document @ later time. picking element guaranteed present @ time delegated event handler attached, can use delegated events avoid need attach , remove event handlers.


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -