首页 > 解决方案 > 在类中创建一个元素,该元素是使用 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>

标签: javascripthtmlexternalappendchild

解决方案


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>


推荐阅读