javascript 用jquery解析完整的html页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4429851/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse complete html page with jquery
提问by Mark Baijens
I load a html with ajax. I want to load the result in a jquery object. I tried that but it returns null. How can I do this? I got a complete page including doctype, head elements and body elements.
我用ajax加载了一个html。我想将结果加载到 jquery 对象中。我试过了,但它返回空值。我怎样才能做到这一点?我得到了一个完整的页面,包括 doctype、head 元素和 body 元素。
var test = $(result); //result contains html code
alert(test.html()); //returns null
I load the data with this function.
我用这个函数加载数据。
function ajaxLoadContent(element) {
    $.ajax({
        url: "url to the page",
        type: "GET",
        timeout: 5000,
        datattype: "html",
        success: function(result) {
        //handler
        },
    });
    return false;
回答by lrsjng
It's a while ago, but maybe you're still interested in it..
这是很久以前的事了,但也许你仍然对它感兴趣..
The intern implementation of $(String)is not able to build an jQuery object that contains heador bodytags. It will simply ignore them and move all elements inside on level up.
的实习生实现$(String)无法构建包含head或body标签的 jQuery 对象。它会简单地忽略它们并将所有元素向上移动。
So if your string is for example
所以如果你的字符串是例如
<html>
  <head>
    <meta ...>
  </head>
  <body>
    <div id="a"/>
  </body>
</html>
the resulting jQuery object will be an array of two elements
生成的 jQuery 对象将是一个包含两个元素的数组
[<meta ...>, <div id="a" />]
to get a body-like jQuery object cut everything but the body content before passing it to jQuery:
要获得一个类似bodyjQuery 的对象,在将它传递给 jQuery 之前,它会剪切除正文内容之外的所有内容:
body = '<div id="body-mock">' + html.replace(/^[\s\S]*<body.*?>|<\/body>[\s\S]*$/ig, '') + '</div>';
var $body = $(body);
now things work as expected.. for example
现在事情按预期工作......例如
$body.find('#a')
Hope that helps..
希望有帮助..
回答by hunter
test is just an html string, so you could simply do this to show the contents
test 只是一个 html 字符串,所以你可以简单地这样做来显示内容
alert(result);
and if you want to bind that to an element
如果你想把它绑定到一个元素
$("#myDiv").html(result);
回答by halfpastfour.am
function ajaxLoadContent(element) {
$.ajax({
    url: "url to the page",
    type: "GET",
    timeout: 5000,
    datattype: "html",
    success: function(data) {
     var result = $(data);
    },
});
return false;
You should now be able to call the result like this (remember it's not added to the DOM yet):
您现在应该能够像这样调用结果(请记住,它还没有添加到 DOM 中):
alert(result.html());
Add to the DOM
添加到 DOM
result.appendTo("body");
Let me know if this works for you.
让我知道这是否适合您。
回答by pawel
Try the loadmethod of jQuery object: http://api.jquery.com/load/
试试loadjQuery对象的方法:http: //api.jquery.com/load/
Load data from the server and place the returned HTML into the matched element.
从服务器加载数据并将返回的 HTML 放入匹配的元素中。

