如何使用jquery读取文件并获取头部和身体的内容? [英] How to read a file using jquery and get content of head and body?

查看:100
本文介绍了如何使用jquery读取文件并获取头部和身体的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取html文件并使用jquery获取head和body标签的内容.但是我没有运气.这是我正在使用的代码.它对我来说很容易找到id或类的内容.但是不带头部和身体标签吗?希望你们能尽快帮助我.谢谢.

I'm trying to read a html file and get the content of head and body tags using jquery. But no luck for me. This is the code i'm using. It worked for me to find the content of a id or a class. But not with head and body tags? Hope you guys can help me out soon. Thanks.

$.get(file, function(response) { alert(response);
        alert($(response).filter('body').html());
                    //is null
                  alert($(response).filter('head').html());
                    //is null
     });

推荐答案

我正在使用手工制作的过滤功能.基本上,它将head,html和meta标记转换为div和段落,这样它们就不会丢失.这是我的功能,您可能需要对其进行调整.

I was using a hand-made filtering function. Basically it converts heads, htmls and meta tags into divs and paragraphs so they don't get lost along the way. This was my function, you might want to adapt it for something else.

function filterInput(sx){

    var t = new Date().getTime();
    var strip_only = function (input,only){only=(((only||"")+"").toLowerCase().match(/<[a-z][a-z0-9]*>/g)||[]).join('');var tags=/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,commentsAndPhpTags=/<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;return input.replace(commentsAndPhpTags,'').replace(tags,function($0,$1){return only.indexOf('<'+$1.toLowerCase()+'>')===-1?$0:'';});};

    sx = sx.replace(new RegExp('<html.*?>','gmi'),'').replace(new RegExp('</html>','gmi'),'');
    /* strip out head & body tags */
    sx = sx.replace(new RegExp('<head.*?>','gmi'),'<div id="u_'+t+'_head">')
        .replace(new RegExp('</head>','gmi'),'</div>')
        .replace(new RegExp('<body.*?>','gmi'),'')
        .replace(new RegExp('</body>','gmi'),'');
    /* replace title tag */
    sx = sx.replace(new RegExp('<title.*?>','gmi'),'<p id="u_'+t+'_title">')
        .replace(new RegExp('</title>','gmi'),'</p>');
    /* replace meta tags */
    sx = sx.replace(new RegExp('<meta','gmi'),'<p');
    sx = strip_only(sx,'<img><link><style>');

    /* wrap */
    sx = $("<div>"+sx+'</div>');

    return sx;
}

这篇关于如何使用jquery读取文件并获取头部和身体的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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