2011-02-23 32 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..."> 

意味着身体元素而来的类属性之后(或者你有重写正则表达式)。