尝试从get()请求返回的html中选择一个"body"标签 [英] Trying to select a 'body' tag from html that is returned by get() request
问题描述
我正在进行 ajax get调用,该操作返回了html页面的内容.我正在尝试选择body
标记的内容,但是我的选择器返回了一个空的jquery对象.
I'm making an ajax get call that returns me contents of html page. I'm trying to select contents of the body
tag but my selector returns an empty jquery object.
$.get(filename, function(data) {
console.log($("body", data));
})
其中data
是html文件的内容.
where data
is contents of html file.
推荐答案
jQuery无法选择响应字符串的body
,因为当使用$()
转换字符串时,<body>
标签会消失.
jQuery cannot select body
of the response string, because the <body>
tag disappears when the string is converted using $()
.
因此,您必须以其他方式从data
字符串中选择主体,例如正则表达式.示例:
Hence, you have to select the body from the data
string in another way, such as Regular expressions. Example:
$.get(filename, function(data) {
var body = data.replace(/^[\S\s]*<body[^>]*?>/i, "")
.replace(/<\/body[\S\s]*$/i, "");
//Optionally, convert the string to a jQuery object:
body = $(body);
console.log(body);
}))
注意:我的正则表达式假定格式正确的HTML文档,其中>
是使用HTML实体正确显示的.如果不是这种情况,则必须使用更高级的RegExp,例如
Note: My Regular Expression assumed a wellformed HTML document, where >
are correctly shown using HTML entities. If this is not the case, more advanced RegExps has to be used, such as the ones shown at this question.
这篇关于尝试从get()请求返回的html中选择一个"body"标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!