获取与其中的内容;身体GT; < /身体GT;字符串中 [英] Get contents of <body> </body> within a string

查看:178
本文介绍了获取与其中的内容;身体GT; < /身体GT;字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做到以下几点。

$("a").click(function (event) {

    event.preventDefault();

    $.get($(this).attr("href"), function(data) {

        $("html").html(data);

    });

});

我想所有超链接的行为做一个AJAX调用和检索HTML。

I want the behavior of all hyperlinks to make a ajax calls and retrieve the html.

不幸的是,你不能简单地取代目前的HTML与您在Ajax响应接收HTML。

Unfortunately you cannot simply replace the current html with the html you receive in the ajax response.

如何才能抓住唯一的东西是在<身体GT; < /身体GT; Ajax响应的标签,这样我可以替代的身在现有的HTML内容

How can grab only what is within the <body> </body> tags of the ajax response so that i can replace only the contents of the body in the existing html.

编辑:&LT的;身体GT; 开始标记不会永远只是&LT;身体GT; 有时可能有一类如:

the <body> opening tag will not always be just <body> it may sometimes have a class e.g.

&LT;体类=class1的Class2的&GT;

推荐答案

如果我理解正确的话,抓住了正则表达式身体标记之间的内容。

If I understand you correctly, grab the content between the body tags with a regex.

$.get($(this).attr("href"), function(data) {
    var body=data.replace(/^.*?<body>(.*?)<\/body>.*?$/s,"$1");
    $("body").html(body);

});

修改

,这里有一个更新,以匹配任何身体标记,不论其属性:

Based on your comments below, here's an update to match any body tag, irrespective of its attributes:

$.get($(this).attr("href"), function(data) {
    var body=data.replace(/^.*?<body[^>]*>(.*?)<\/body>.*?$/i,"$1");
    $("body").html(body);

});

正则表达式是:

The regex is:

^               match starting at beginning of string

.*?             ignore zero or more characters (non-greedy)

<body[^>]*>     match literal '<body' 
                    followed by zero or more chars other than '>'
                    followed by literal '>'

(               start capture

  .*?           zero or more characters (non-greedy)

)               end capture

<\/body>        match literal '</body>'

.*?             ignore zero or more characters (non-greedy)

$               to end of string

添加我切换到匹配大写和小写。

Add the 'i' switch to match upper and lowercase.

和请忽略我的关于S开关评论,在JavaScript中所有的正则表达式已经单行默认情况下,添加敢'来匹配多行的模式。 (该死的Perl,干扰了我,当我写的JavaScript: - !)

And please ignore my comment regarding the 's' switch, in JavaScript all RegExp are already single-line by default, to match a multiline pattern, you add 'm'. (Damn you Perl, interfering with me when I'm writing about JavaScript! :-)

这篇关于获取与其中的内容;身体GT; &LT; /身体GT;字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆