解析与jQuery完整的HTML页面 [英] Parse complete html page with jquery

查看:147
本文介绍了解析与jQuery完整的HTML页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我加载使用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对象将有两个元件的阵列

  [<元...&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(/^[\s\S]*<body.*?>|<\/body>[\s\S]*$/ig, '') + '</div>';
var $body = $(body);

now things work as expected.. for example

$body.find('#a')

Hope that helps..

这篇关于解析与jQuery完整的HTML页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆