2013-06-01 119 views
0

如何使用Ajax加載對象並將函數應用於它們?ajax加載內容上的jquery函數

此代碼有效,但我希望此代碼在沒有點擊事件的情況下運行。所以它會自動運行。

$(document).on("click",".button",function(e){ 

    var imgcount = $('.slider img').length; 
    var slidesize = 100/imgcount 
    var innersize = 100 * imgcount 

    $('.slider img').wrap('<div class="slide" />'); 
    $('.slide').wrapAll('<div class="inner" />'); 
    $('.inner').wrapAll('<div class="overflow" />'); 
    $('.slide').css('width', slidesize + '%'); 
    $('.inner').css('width', innersize + '%'); 

    }); 

這是我在我的內容

$('.work-item-hover').click(function(){ 

    var toLoad = $(this).attr('href')+' #content-post > *'; 
    $('#content-post').slideUp('normal',loadContent); 
    $('#load').remove(); 
    $('.content-post-wrap').append('<span id="load">LOADING...</span>'); 
    $('#load').fadeIn('normal'); 
    window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5); 
    function loadContent() { 
     $('#content-post').load(toLoad,'',showNewContent()) 
    } 
    function showNewContent() { 
     $(document).ajaxComplete(function(){ 
    $('#content-post').slideDown('slow',hideLoader()); 
}); 
+0

我沒有看到AJAX來這裏發揮作用,請詳細說明。否則'$(document).ready(...)'可能是您最簡單的解決方案。 – zsawyer

+0

所有這些元素(滑塊img,幻燈片,內部)他們都加載與Ajax。 – beliy333

+0

也許,而不是onclick註冊這個函數(或執行它)你的ajax調用的成功方法? – zsawyer

回答

0

在你的情況下,showNewContent()是你的成功方法。你可以在那裏插入你的代碼(或者爲了方便將它包裝在另一個命名的函數中)。

function showNewContent() {  

    var imgcount = $('.slider img').length; 
    var slidesize = 100/imgcount 
    var innersize = 100 * imgcount 

    $('.slider img').wrap('<div class="slide" />'); 
    $('.slide').wrapAll('<div class="inner" />'); 
    $('.inner').wrapAll('<div class="overflow" />'); 
    $('.slide').css('width', slidesize + '%'); 
    $('.inner').css('width', innersize + '%'); 

    $('#content-post').slideDown('slow',hideLoader()); 
} 

注意,我去掉了調用.ajaxComplete(),因爲它自showNewContent()註冊到​​爲complete handler這裏.load(toLoad,'',showNewContent())(且僅此單個請求)是恕我直言多餘的。通過您的原始呼叫,您可以註冊所有ajax請求。

sandboxed test

+0

謝謝!太棒了! – beliy333

1

觸發的點擊事件如何加載明確

$('.slide').css('width', slidesize + '%'); 
    $('.inner').css('width', innersize + '%'); 
}).click(); 
0

$(document).ready(function(){}); - 除此之外,請確保您的通話$('element').click();在你成功任何AJAX請求的功能。