javascript - 在类中创建一个元素,该元素是使用 javascript *no jquery 包含的 html 的一部分
问题描述
我正在尝试通过XMLHttpRequest将一些 HTML 代码加载到我的 index.html 中。但是通过将收到的 HTML 代码附加到我的 index.html 中的另一个标记来阻止我。
这是我的带有 XMLHttprequest 的 index.html:
<header id="header"></header>
<script>
if (document.body.contains(document.getElementById('header'))) {
var reqHeader = new XMLHttpRequest();
reqHeader.onload = function () {
document.getElementById('header').appendChild(this.responseText);
}
reqHeader.open('get', 'header.html', true);
reqHeader.send();
}
</script>
这是我的 header.html 文件的内容:
<div id="headerWrapper">
<ul>
<li id="foo">1</li>
</ul>
</div>
解决方案
XMLHttpRequest 返回的内容是一个字符串。您可以使用 javascript XMLParser解析该字符串,这将返回一个 DOM 元素,您可以使用通常的 javascript DOM 访问语法访问该元素。
所以在你的 XMLHttpRequest 中,使用下面的代码
const parser = new DOMParser().parseFromString(htmlString, 'text/html');
document.getElementById('header').appendChild(parser.querySelector('#headerWrapper'));
由于跨源策略而没有 XMLHttpRequest 的简化示例:
if (document.body.contains(document.getElementById('header'))) {
var htmlString = '<div id="headerWrapper"><ul><li id="foo">1</li><li id="bar">2</li></ul></div>';
const parser = new DOMParser().parseFromString(htmlString, 'text/html');
document.getElementById('header').appendChild(parser.querySelector('#headerWrapper'));
}
document.getElementById('foo').classList.add('test');
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<header id="header"></header>
</body>
</html>
推荐阅读
- java - 如何制作会发生变化的圆形碰撞箱?
- sql - 如何在不写 where 条件的情况下在查询中使用时间函数?
- android - 从 xml 调用 View Model 方法不会在 android 中调用问题
- android - 使用 Work Manager 更新网络请求的逻辑
- c++ - (Rcpp)armadillos abs() 函数在 std::abs 工作时与 c++ double 一起使用时输出错误值
- python - 在 Python 中遍历另一个脚本的不同类
- c# - 如何在当前方法中使用数据库事务?
- google-apps-script - 谷歌工作表按钮在移动设备上不起作用
- r - R中的命令filter()有问题吗?match.arg(method) 中的错误:“arg”必须为 NULL 或字符向量
- sql - 插入查询 - 将数据类型 nvarchar 转换为 (null) 时出错