So I'm adding elements to index.php through a foreach loop in a file called ajaxLoad.php, that's loaded using jQuery's load().
The problem is that jQuery can't find those elements when I try to select them. I know that ajaxLoad.php hasn't finished printing out messages. When I try to select the delete class anchors with jQuery, jQuery can't find them.
<div class="messages">
<!--these are added by the foreach loop-->
<a href="#" class="delete">Delete</a>
</div>
A probably important note is that the delete class is not in the index.php markup, they're only added through load(). Here is the inline jQuery:
<script>
$(function(){
//adds messages to a div
$('.messages').load('ajaxLoad.php');
//later on...
$('.delete').click(function(){
alert('Hey');
//nothing happens
});
});
</script>
I've looked into $(window).load(function(){}) but it doesn't seem to work. I would be glad for help! thanks!
Put it in the callback function, see the manual :
$('.messages').load('ajaxLoad.php', function() {
$('.delete').click(function(){
alert('Hey');
});
});
Or use event delegation :
$('.messages').load('ajaxLoad.php');
//later on...
$('body').on('click', '.delete', function() {
// ^^^^ any containing element that is already there on page-load
alert('Hey');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.