从AJAX请求获取页面内容后,我可以选择标签元素,但不能选择正文元素 [英] After getting a page's content from an AJAX request I can select tag element but cannot select body element

查看:284
本文介绍了从AJAX请求获取页面内容后,我可以选择标签元素,但不能选择正文元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过AJAX请求获得了html页面

I got an html page through an AJAX request

$.ajax({
    async: true,
    method: 'GET',
    url: linkPage,
    // cache: true,
    success: function (data) {
        console.log(data);
    }
});

我得到的数据格式如下:

The data format I get like this:

<!DOCTYPE html>
<html>
<head>
...
</head>
<body id="sustainable" class='sustainable'>
<div id="wrap">
    <main class="temp>
        <section class="sec01">
            ...
        </section>
    </main>
</div>
</body>
</html>

现在,我想通过以下代码获取主体ID和类别( 可持续" ):

Now I want to get the body id and class (which is "sustainable") via this code:

$(data).find('body').attr('class');

但是我不知道为什么我不能得到它,它返回 undefiend .但是,当我通过此代码获取html内容或<main>的类时:

But I have no idea why I can't get that, it returns undefiend. But when I get html content or class of <main> by this code:

$(data).find('main').attr('class');
$(data).find('main').html();

它恰好返回我想要的.谁能解释我为什么?

It returns exactly what I want. Can anybody explain me why?

到目前为止,我已经通过创建这样的虚拟DOM尝试了一些解决方案,并且可以根据需要从AJAX数据中选择<body><main>:

I've tried some solutions so far by create a virtual DOM like this, and I can select <body> and <main> from AJAX data as I want: Cannot get body element from ajax response

但是我仍然想知道为什么我不能选择<body>类和html作为第一种情况?

But I still wonder why I can't select <body> class and html as first case?

推荐答案

jQuery

如果HTML比不带属性的单个标签更为复杂(如上例所示),则元素的实际创建由浏览器的.innerHTML机制处理.在大多数情况下,jQuery创建一个新的<div>元素并将该元素的innerHTML属性设置为传入的HTML代码段.

If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's .innerHTML mechanism. In most cases, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in.

由于<div>中不能包含<body>,因此浏览器将忽略<body>标记.

Since you can't have a <body> inside a <div>, the browser ignores the <body> tag.

文档继续说:

在传递复杂的HTML时,某些浏览器可能不会生成完全复制提供的HTML源代码的DOM.如前所述,jQuery使用浏览器的.innerHTML属性来解析传递的HTML,并将其插入到当前文档中.在此过程中,某些浏览器会过滤掉某些元素,例如<html><title><head>元素.因此,插入的元素可能不代表所传递的原始字符串.

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, jQuery uses the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.

这篇关于从AJAX请求获取页面内容后,我可以选择标签元素,但不能选择正文元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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