2012-06-28 81 views
2
$(document).ready(function(){ 

$(function() { 
    $('a.ajaxload').click(function(e) {   
     var url = $(this).attr('href'); 
     $('#desktopcontainer').load(url); // load the html response into a DOM element 
     e.preventDefault(); // stop the browser from following the link 
    }); 
}); 

$(function() { 
    $(".accordion .accordion-tabs .tab").each(function(){ 
     $(this).click(function(){ 
      if ($(this).hasClass('tab')){ 
      $(this).removeClass('tab'); 
      $(this).addClass('active'); 
      }else{ 
      $(this).removeClass('active'); 
        $(this).addClass('tab'); 
      } 

      $(this).next().slideToggle('slow'); 
       return false; 
     }); 
    }); 
}); 
}); 

我的標籤工作正常,但在點擊「a.ajaxload」將內容添加到頁面後,我的標籤不再響應。加載後jQuery事件不起作用

任何人都可以請告訴我問題在哪裏?

已解決!

我所做的是在我的加載後添加函數......查看下面的新代碼並查看其差異。我希望它能幫助別人。

$(document).ready(function(){ 

initDashboard(); 

$(function() { 
    $('a.ajaxload').click(function(e) {   
     var url = $(this).attr('href'); 
     $('#desktopcontainer').load(url); // load the html response into a DOM element 
     e.preventDefault(); // stop the browser from following the link 
     initDashboard(); 
    }); 
}); 

function initDashboard() { 
    $(".accordion .accordion-tabs .tab").each(function(){ 
     $(this).click(function(){ 
      if ($(this).hasClass('tab')){ 
      $(this).removeClass('tab'); 
      $(this).addClass('active'); 
      }else{ 
      $(this).removeClass('active'); 
        $(this).addClass('tab'); 
      } 

      $(this).next().slideToggle('slow'); 
       return false; 
     }); 
    }); 
} 

}); 
+0

謝謝你,我已經做到了。 – Shina

+1

你能告訴我們你的html代碼嗎? –

+0

也許點擊應該也是'活的'(注意:在jQuery 1.7+中你應該使用'on')?它加載了什麼內容?你可以發佈一個jsfiddle> –

回答

2

你需要on(),因爲它是動態添加(例如,通過load方法插入):

$('.accordion .accordion-tabs').on('click', '.tab', function(){ 
    if ($(this).hasClass('tab')) { 
     $(this).removeClass('tab'); 
     $(this).addClass('active'); 
    }else{ 
     $(this).removeClass('active'); 
     $(this).addClass('tab'); 
    } 

    $(this).next().slideToggle('slow'); 
     return false;  
    }); 
}); 

也沒必要使用jQuery準備處理三次,只是把所有的jQuery的相關這裏面的代碼:

$(document).ready(function(){ 

}); 

文檔:

+0

on()看起來什麼都不做 - 即使用戶第一次進入頁面。這就是我首先使用live()的原因。任何原因? – Shina

+0

@Shina:它是最新的jQuery版本的一部分,請嘗試使用它的最新版本。 – Blaster