2016-09-28 98 views
1

我已經使用來自jQuery的​​在單獨的html文件中包含我的標題&頁腳。我的jQuery代碼如下:如何將類添加到通過jquery加載的html文件?

$(function(){ 
    $("#header").load("page-component/header.html"); 
    $("#footer").load("page-component/footer.html"); 
}); 

現在,當我瀏覽到另一個網頁,我想一個active類添加到我的頁眉/頁腳環節之一,但我似乎無法做到這一點。任何人都可以幫助我?

我已經試過這樣的事情,但它沒有工作:

$(document).ready(function(){ 
    jQuery('#menu-about').addClass('active'); 
}); 

回答

3

使用jQuery.load方法complete callback

.load(url [, data ] [, complete ])

當你調用的元素addClass方法,element不存在DOMcallback函數被調用時external文件中指定element

$(function() { 
    $("#header").load("page-component/header.html", function() { 
    jQuery('#menu-about').addClass('active'); 
    }); 
    $("#footer").load("page-component/footer.html", function() { 
    jQuery('#menu-about').addClass('active'); 
    }); 
}); 
+0

感謝loaded ,這工作。 –

+1

@JoshuaRajandiran - 我很高興它有幫助! _快樂編碼_ – Rayon

相關問題