从$ .get()对象的获取“class”attr
我需要从$ .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包含整个响应的字符串。
如果您获得完整的HTML文档响应,则不会在浏览器之间获得一致的行为。
有些浏览器会剥离head
和body
元素。
你可以尝试这个,但没有保证:
var fullContent = '' + response + ''; var bodyclass = $(fullContent).find("body").attr("class"); $("body").attr("class", bodyclass);
这是从$.get
获取body类的解决方案。
$.get(url, refreshFullContent); var refreshFullContent = function(response, status, xhr) { $("body").attr("class", /body([^>]*)class=(["']+)([^"']*)(["']+)/gi.exec(response.substring(response.indexOf("
我尝试了user113716的解决方案,但不幸的是,身体类总是未定义的。 但这个解决方案对我有用:
$("body").attr("class", data.match(/body class=\"(.*?)\"/)[1]);
虽然数据是我的ajax响应,并且body必须如下所示:
意味着在body元素到达class属性之后(或者你必须重写正则表达式)。
$("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"); }); });