I want to know why is that my javascript functions won’t work if my html tag is from the php script??
Here’s my jquery code:
$(function () {
//functions don't work
$('ul li:gt(4)').hide();
$('.prev').click(function() {
var first = $('ul').children('li:visible:first');
first.prevAll(':lt(5)').show();
first.prev().nextAll().hide()
});
$('.next').click(function() {
var last = $('ul').children('li:visible:last');
last.nextAll(':lt(5)').show();
last.next().prevAll().hide();
});
//end of functions don't work
$('.load').click(function() {
$.ajax({
url: 'load.php',
success:function(data){
$('#paging-container').html(data);
}
});
});
});
Here’s my html code:
<input class="load" type="button" value="Load">
<div id="paging-container">
</div>
And here’s my php script:
<?php
echo '<ul>';
for($i=1;$i<=50;$i++){
echo '<li>'.$i.'</li>';
}
echo '</ul>
<a class="prev">prev</a> | <a class="next">next</a>';
?>
For the type of jQuery you’re using, the HTML tags must exist in your page already at the time you are running the initial jQuery. As it is, they do not exist and thus no event handlers are attached to them.
You have a couple choices to correct that:
.on()Using the dynamic form of
.on()would look like this:Here the event handler is actually attached to
#paging-containerand it uses delegated event handling to catch the events that happen on child objects. This will work even if child objects are added/removed after the event handler is installed as long as#paging-containeritself is not destroyed.See this post for a general description of how the dynamic flavor of
.on()works.