【发布时间】:2020-01-07 07:28:25
【问题描述】:
我通过 AJAX 请求获得了一个 html 页面
$.ajax({
async: true,
method: 'GET',
url: linkPage,
// cache: true,
success: function (data) {
console.log(data);
}
});
我得到的数据格式是这样的:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body id="sustainable" class='sustainable'>
<div id="wrap">
<main class="temp>
<section class="sec01">
...
</section>
</main>
</div>
</body>
</html>
现在我想通过以下代码获取 body id 和类("sustainable"):
$(data).find('body').attr('class');
但我不知道为什么我不能得到它,它返回 undefiend。但是当我通过这段代码获得<main>的html内容或类时:
$(data).find('main').attr('class');
$(data).find('main').html();
它返回的正是我想要的。谁能解释一下为什么?
到目前为止,我已经通过创建这样的虚拟 DOM 尝试了一些解决方案,我可以根据需要从 AJAX 数据中选择 <body> 和 <main>:Cannot get body element from ajax response
但我仍然想知道为什么我不能选择<body> class 和 html 作为第一种情况?
【问题讨论】:
-
您是否尝试过使用 document.getElementById("sustainable"); ?或者使用 JQuery $("#sustainable") 使用它的 id 或使用 $(".sustainable") 使用类名?
标签: javascript jquery ajax