2012-03-19 58 views
1

我正在嘗試閱讀一個html文件,並使用jquery獲取頭部和身體標記的內容。但對我來說沒有運氣。這是我使用的代碼。它爲我找到了一個id或一個類的內容。但不是與頭部和身體標籤?希望你們能儘快幫助我。謝謝。如何使用jquery讀取文件並獲取頭部和身體的內容?

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

提醒事情可能會非常惱人。你應該使用'console.log()'(假設你有Firefox或Chrome)。 – mowwwalker 2012-03-19 04:36:18

回答

0

我正在使用手工過濾功能。基本上,它會將頭像,htmls和元標記轉換爲div和段落,這樣他們就不會迷路了。這是我的功能,你可能想要適應其他的東西。

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; 
} 
+0

好吧,如果我使用這個,我該如何改變這個來找到頭部或身體的內容? – guitarlass 2012-03-19 04:56:45

+0

刪除'var t = new Date()。getTime()'並將其作爲函數參數(函數filterInput(sx **,t **))傳遞。然後使用'var t = new Date()。getTime(); var html = filterInput(response.responseText,t); var head = $('div#u _'+ t +'_ head',html); var title = $('p#u _'+ t +'_ title'); // ...'。對於身體刪除身體/身體標記,並使其看起來像頭,只需閱讀代碼,它很容易,它是有道理的。 – 2012-03-19 07:03:13