我正在制作一个ajax get call返回 html 页面的内容。我正在尝试选择 body
标记的内容,但我的选择器返回一个空的 jquery 对象。
$.get(filename, function(data) {
console.log($("body", data));
})
其中data
是html文件的内容。
最佳答案
jQuery 无法选择body
响应字符串的,因为 <body>
当使用 $()
转换字符串时,标签消失.
因此,您必须从data
中选择正文字符串以另一种方式,例如正则表达式。示例:
$.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 实体正确显示。如果不是这种情况,则必须使用更高级的正则表达式,例如 this question 中所示的正则表达式。 .
关于jquery - 尝试从 get() 请求返回的 html 中选择 'body' 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7839889/