2011-02-23 30 views
1

我需要從使用$ .get()檢索的頁面對象的body元素中獲取class屬性。在下面的示例所示,fullContent被設置爲對象,但我不能選擇body元素...我寧願不訴諸文本操作來得到這個

$.get(url, refreshFullContent); 

var refreshFullContent = function(response, status, xhr) 
{ 
    fullContent = response; 
    var bodyclass = $(fullContent).find("body").attr("class"); 
    $("body").attr("class", bodyclass); 
} 

有沒有辦法用得到這個對象上的選擇器(就像我在這個例子中所做的那樣)?如果沒有,從文本中得到這個最好的方法是什麼? xhr.responseText包含整個響應的字符串。

回答

2

如果您得到完整的HTML文檔響應,您將無法在瀏覽器之間獲得一致的行爲。

某些瀏覽器會剝離headbody元素。

你可以試試這個,但不保證:

​​
+0

感謝您試圖幫助,但這並沒有奏效。我將嘗試使用$ .ajax方法而不是$ .get – andrhamm 2011-02-24 13:23:10

+0

@andrhamm:不幸的是,使用'.ajax'不會給出任何不同的結果。 '$ .get'只是'$ .ajax' GET請求的便捷包裝。你是否證實'response'實際上包含你期望的內容? – user113716 2011-02-24 13:43:39

+0

是的,它包含我請求的整個HTML文檔。奇怪的是,我可以從響應中獲取任何其他元素。我將一個特定元素放入頁面中(但是該元素的樣式受到body類的影響)。我的解決方法是打印(服務器端)相同的類從身體標記到我可以選擇的元素中的數據屬性。從那裏我可以這樣做:'var bodyclass = $(「。content.lower」)。attr(「data-bodyclass」);'then'$(「body」)。removeClass()。addClass(bodyclass); ' – andrhamm 2011-02-24 15:45:54

3

這裏是一個解決方案,從$.get獲得體類。

$.get(url, refreshFullContent); 
var refreshFullContent = function(response, status, xhr) 
{ 
    $("body").attr("class", /body([^>]*)class=(["']+)([^"']*)(["']+)/gi.exec(response.substring(response.indexOf("<body"), response.indexOf("</body>") + 7))[3]); 
} 
+0

酷..工作.. – commonpike 2013-02-14 14:00:10

1
$("a").click(function (e) { 
    e.preventDefault(); 

    $.get(this.pathname, function(response) { 
     var $dom = $(document.createElement("html")); 
     $dom[0].innerHTML = response; // Here's where the "magic" happens 

     var $body = $(dom).find("body"); 
     // Now you can access $body as jquery-object 
     // $body.attr("class"); 

    }); 
}); 
2

我試圖user113716的解決方案,但不幸的是,體類總是不確定的。但是這種解決方案對我的作品:

$("body").attr("class", data.match(/body class=\"(.*?)\"/)[1]); 

,而數據是我的Ajax響應和身體已經這個樣子:

<body class="classname..."> 

意味着身體元素而來的類屬性之後(或者你有重寫正則表達式)。