我正在编写一个应用程序,它通过 AJAX 获取一堆 JSON 数据,然后渲染由 es6 模板文字中的相同数据构造的 View 。非常简单的演示版本:
let mountPoint = document.getElementById("mountPoint");
let view = document.createElement("section");
view.id = "view";
view.innerHTML = `<section>${returnedAjaxData}</section>`;
mountPoint.innerHTML = view;
#mountPoint {
background: #000000;
}
#view {
background: #444444
}
<html lang="en">
<head>
<meta charset="utf-8">
<title>My App</title>
</head>
<body>
<section id="mountPoint"></section>
</body>
</html>
其中 ${returnedAjaxdata} 是从 Ajax 调用返回的数据(此处未显示,但工作正常)
问题是“#mountPoint”有黑色背景,但“#view”没有灰色背景。看起来 CSS 文件是在“#view”渲染之前运行的,因为它在渲染之前等待 Ajax 数据。
编辑 我知道如何在 AJAX 成功时更改特定元素的 CSS。我的问题是在 AJAX 调用返回并且 DOM 渲染后如何运行整个样式表。对于上下文 - 整个应用程序将位于“#mountPoint”内,因此更新单个元素不会有太大帮助
一种可能的解决方案是在渲染“#view”之后编写 styles.min.css 文件,但这看起来很老套……我想知道:React 和其他 View 渲染框架是如何做到这一点的?它们也会在读取 CSS 文件后渲染 HTML,对吗?有没有一个好的模式可供我学习?
最佳答案
Element#innerHTML解析一个字符串,并将其设置为节点的 html 内容。您使用 Document#createElement 创建的节点不是一个字符串。当您尝试使用 Element#innerHTML 将其添加到 mountPoint
时,它会转换为字符串,并且该字符串没有 ID view
。
您需要使用 Node#appendChild 将节点附加到 View 中或ParentNode#append (MS 浏览器不支持)。
此外,CSS 选择器(例如 id)区分大小写,CSS 中的 mountpoint
与 html 中的 mountPoint
不同。
let mountPoint = document.getElementById("mountPoint");
let view = document.createElement("section");
view.id = "view";
view.innerHTML = `<section>returnedAjaxData</section>`;
mountPoint.appendChild(view); // append as a child of mountPoint
#mountPoint { /** renamed to mountPoint **/
height: 40px; /** just for the example **/
background: #000000;
}
#view {
background: #444444
}
<section id="mountPoint"></section>
如果 CSS 和 HTML 中的 id 完全相同,Element#innerHTML 也可以工作:
let mountPoint = document.getElementById("mountPoint");
mountPoint.innerHTML = '<section id="view">returnedAjaxData</section>';
#mountPoint { /** renamed to mountPoint **/
height: 40px; /** just for the example **/
background: #000000;
}
#view {
background: #444444
}
<section id="mountPoint"></section>
关于javascript - 如何将 CSS 样式应用于 AJAX 调用后呈现的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45294817/