jQuery: Use a plugin on a page pulled in via AJAX
I'm building a simple AJAX driven website (because of the audience, it's okay to do this) where pages are pulled in based on the anchor etc. Simple enough.
However, one of the pages I want to pull in should have a slideshow on it. Once the call is successful and the page appears, the plugin isn't working.
Do I have to re-initialize the plugins I want to use on a page that's dynamically pulled in?
I can't show any code right now but in theory, what would the best practice be to use plugins开发者_开发技巧 and re-init JS code on dynamic pages?
I usually have all my script in one jquery.scripts.js file in the head of the main index page. Do these scripts need to be on the separate pages themselves?
Many thanks! Michael.
$('#logo a').click(function() {
$.ajax({
type: "POST",
url: "./ajax/test.html",
data: '',
dataType: "html",
success: function(data){
if(parseInt(data)!=0) {
$('#cycle').html(data);
$("#cycle").cycle({
fx: 'fade',
//easing: 'easeOutExpo',
speed: 3000,
//timeout: 0,
//next: '#cycle-next',
//prev: '#cycle-prev'
});
}
}
});
return false;
});
This code executes the call, loads the page, but does not re-init the plugin. It does nothing, and there are no errors. Weird.
What you should do is after you retrieved the ajax page, insert it into your website and when that is done you can initialize the slideshow.
so basically:
$.ajax({
url: 'myurl',
success: function (data) {
$('#target').html(data);
$('#target .slideshow').slideshow();
}
});
<div id="#target">
<div class="slideshow"></div>
</div>
You don't say whether the cycle plugin has been previously initialized before running the $.ajax command. If it been, then you'll need to destroy the cycle slideshow and re-initialize it.
success:function(data){
if(parseInt(data)!=0) {
$('#cycle').html(data);
$('#cycle').cycle('destroy');
$("#cycle").cycle({
fx:'fade',
//easing:'easeOutExpo',
speed:3000,
//timeout:0,
//next:'#cycle-next',
//prev:'#cycle-prev'
});
}
}
精彩评论