解析与jQuery完整的HTML页面完整、页面、jQuery、HTML

由网友(⒈場遊戲⒈場夢)分享简介:我加载使用AJAX一个HTML。我想,将结果在一个jQuery对象。我试过,但它返回null。我怎样才能做到这一点?我有一个完整的页面,包括文档类型,头部元素和body元素。VAR测试= $(结果); //结果包含HTML code警报(test.html的()); //返回null我加载数据使用此功能。函数ajax...

我加载使用AJAX一个HTML。我想,将结果在一个jQuery对象。我试过,但它返回null。我怎样才能做到这一点?我有一个完整的页面,包括文档类型,头部元素和body元素。

  VAR测试= $(结果); //结果包含HTML code
警报(test.html的()); //返回null
 

我加载数据使用此功能。

 函数ajaxLoadContent(元){
    $阿贾克斯({
        网址:URL的网页,
        键入:GET,
        超时:5000,
        datattype:HTML,
        成功:函数(结果){
        //处理程序
        },
    });
    返回false;
 

解决方案

这是前一段时间,但也许你仍然感兴趣。

实习生实施 $(字符串)是不是能够建立一个包含或jQuery对象标签。它会简单地忽略他们,把所有元素中的水平了。

所以,如果您的字符串例如:

 < HTML>
  < HEAD>
    <元...>
  < /头>
  <身体GT;
    &所述;股利的id =一个/>
  < /身体GT;
< / HTML>
 
JQuery 18 JQuery 节点的 HTML 和值的管理

所得jQuery对象将有两个元件的阵列

  [<元...&GT中,< DIV ID =A/>]
 

获得般的jQuery对象传递给jQuery的前削减一切,但正文内容:

 人体='< D​​IV ID =身体模拟> + html.replace(/ ^ [ S  S] *<身体*> |。?<  /身体GT; [ S  S] * $ / IG,'')+'< / DIV> ';
变量$身体= $(身体);
 

现在按预期工作的事情..例如:

  $ body.find('#A')
 

希望有所帮助。

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.

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;

解决方案

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 head or body tags. It will simply ignore them and move all elements inside on level up.

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

[<meta ...>, <div id="a" />]

to get a body-like jQuery object cut everything but the body content before passing it to jQuery:

body = '<div id="body-mock">' + html.replace(/^[sS]*<body.*?>|</body>[sS]*$/ig, '') + '</div>';
var $body = $(body);

now things work as expected.. for example

$body.find('#a')

Hope that helps..

阅读全文

相关推荐

最新文章