2012-08-23 25 views
0

我有一些代碼在這裏加載一個外部頁面,當然取代了正文和它的內容。除了body標籤有一些我想要檢索的屬性,而不是通過.css嵌入標籤之外,這很好。我無法更改頁面,因爲有成千上萬的頁面。任何的意見都將會有幫助。如何使用jQuery檢索和設置身體屬性時,不css

代碼加載頁面:

$(document).ready(function() { 
    $('[id=Page]').load($(JQCurrentPagelink).val(), function() { 
}); 

樣品身體標記:

<body background="/Image/ReviewFade02.jpg" leftmargin="20" topmargin="20" marginwidth="20" marginheight="20"> 
+0

對不起,正文屬性在這裏:background =「/ TracksImage/ReviewFade02.jpg」leftmargin =「20」topmargin =「20」marginwidth =「20」marginheight =「20」 –

+0

它可能是瀏覽器,而不是JQuery這個。看到這裏:http://stackoverflow.com/questions/2488839/does-jquery-strip-some-html-elements-from-a-string-when-using-html – jonkroll

+0

即使我必須打兩個電話一搶body標籤屬性然後設置主體,然後使用.load檢索文件,我很好,如果沒有更好的方法。無論是我還是解析所有.html頁面的內容併爲每個頁面創建一個css頁面。 –

回答

0

試試這個:

$.ajax({ 
    url: 'page-to-load.html', 
    success: function(data) { 
     // load the content of the other page into #ajax-div 
     $('#ajax-div').html(data); 
     // a RegEx pattern to grab the opening body tag 
     var pattern=new RegExp("<body.*>"); 
     // grab the opening body tag 
     var bodyOpeningTag = pattern.exec(data)[0]; 
     // remove everything we don't need ('<body ', '>' and quotes) 
     var bodyAttributesString = bodyOpeningTag.replace('<body ', ''); 
     bodyAttributesString = bodyAttributesString.replace('>', ''); 
     bodyAttributesString = bodyAttributesString.replace(/\"/g,''); 
     // split the string into a one dimensional array ('background=/images/about.jpg', 'leftmargin=20' etc) 
     var bodyAttributesArray = bodyAttributesString.split(' '); 
     // split each attribute item into a [attributename, value] array 
     var bodyAttributesArray2d = new Array(); 
     for (var i = 0; i < bodyAttributesArray.length; i++) { 
      bodyAttributesArray2d[i] = bodyAttributesArray[i].split('='); 
     } 
    } 
}); 

演示這裏是頁:

jQuery - ajax load another page and grab body attributes