从ajax页面的body元素中提取所有类,替换当前页面的body类

Extract all classes from body element of AJAX-ed page and replace current page's body classes

本文关键字:body 当前页 替换 ajax 元素 提取      更新时间:2023-09-26

我正在ajax化一个带有持久音乐播放器的WordPress主题。Wordpress在<body>标签上使用动态类。基本结构如下:

<html>
    <head>
    </head>
    <body class="unique-class-1 unique-class-2 unique-class-3">
        <div id="site-container">
            <nav class="nav-primary">
                <a href="/other-page-01/">Other Page 01</a>
                <a href="/other-page-02/">Other Page 02</a>
            </nav>
            <div class="site-inner">
                <p>Site Content Here</p>
            </div>
        </div>
        <div id="music-player"></div>
    </body>
</html>

我目前正在使用load('/other-page-01/ #site-container')成功加载/other-page-01/, /other-page-02/等内容。但是,我需要从AJAX加载的页面中提取所有<body>类,并动态地用它们替换当前页面的<body>类。

注意:由于<div id="music-player">是持久的,所以不能替换整个<body>元素。我试过jQuery.get(),但不能让它工作。

我如何从AJAX请求的页面提取<body>类并用它们替换当前页面的<body>类?

我不是很熟悉jQuery或Javascript,所以确切的代码将是非常有帮助的。如有任何帮助,不胜感激。

谢谢,亚伦

我的典型解决方案是告诉您将AJAX代码扔到jQuery对象中,然后像正常一样读取它:

$(ajaxResult).attr('class');

有趣的是,似乎你不能对<body>元素这样做。

我想说最简单的解决方案(如果你能控制生成的HTML)就是使用一些好的正则表达式:

var matches = ajaxResult.match(/<body.*class=["']([^"']*)["'].*>/),
    classes = matches && matches[1];

我说"如果你能控制生成的HTML",因为这依赖于HTML的合理格式。

另一种方法是将其解析为DOMDocument,然后提取所需的内容,但这需要更多的时间,并且在这样的简单情况下通常是多余的。

将返回的html中的正文转换为具有特定ID的div,然后以该ID为目标获取正文(现在是div)的类

modifiedAjaxResult = ajaxResult.replace(/<body/i,'<div id="re_body"')
                               .replace(/<'/body/i,'</div');
$(modifiedAjaxResult).filter("#re_body").attr("class");

当然,如果主体有一个id,这将与它冲突,所以任意的数据属性可能不太可能破坏。

modifiedAjaxResult = ajaxResult.replace(/<body/i,'<div data-re-id="re_body"')
                               .replace(/<'/body/i,'</div');
$(modifiedAjaxResult).filter("[data-re-id=re_body]").attr("class");
http://jsfiddle.net/N68St/

当然,要使用这种方法,您必须切换到使用$。得到相反。

$.get("/other-page-01/",function(ajaxResult){
    var modifiedAjaxResult = ajaxResult.replace(/<body/i,'<div data-re-id="re_body"')
                                   .replace(/<'/body/i,'</div');
    alert($(modifiedAjaxResult).filter("[data-re-id=re_body]").attr("class"));
    // the following line replicates what `.load` was doing.
    $(someElement).append( $("<div>").html(ajaxResult).find("#site-container") );
});