javascript - 在 html 中存储动态内容数据的最佳实践是什么?
问题描述
基本上,我正在创建一个简单的宣传册网站,可以使用 Javascript 动态更改内容。每次单击该按钮时,它都会调用 .js 文件中的一个函数,该函数将其插入到 html 中。为此,我将这些数据放入 .js 文件中的变量中。问题是我发现数据太大并且 .js 文件混乱。
<button class="content-1">
<button class="content-2">
<div class="container">
# change between content 1 and 2
</div>
// in my case there are more than 2 contents
// each content has other contents as well
// the question is where to put these data
let contentOne = [
"a lot of text data",
"a lot of text data",
"a lot of text data"
]
# other code
现在我设法将它们分成另一个 .js 文件。但我只是想知道,是否有一种更清洁的方式来存储然后访问这些数据?喜欢使用 YAML 吗?你通常是怎么做的?
对于动态网站,我意识到它通常存储在数据库中,但是对于静态网站来说呢?
解决方案
我会将它作为 JSON 放在不同的文件中。然后在您的 HTML 文件中,您有一个函数执行获取请求以从服务器获取 JSON 文件。
这确实意味着您在开发时需要一个网络服务器。您可以使用轻量级的http-server。
然后,您的代码执行以下操作:
function hydrateData() {
return fetch('data.json').then(response => response.json());
}
hydrateData().then(data => {
// the rest of your code that needs the data goes in here
})
推荐阅读
- c++ - 如何从动态数组中删除
- sharepoint - Power BI - 有条件地向值添加天数
- python - 我试图查看一个列表的任何值是否与另一个列表的任何值匹配,但我不能这样。请帮忙!..我不明白为什么
- excel - excel一个单元格中的数据想分成多个单元格
- kotlin - Dagger 2 组件保留旧参考
- html - 如何正确格式化我的导航栏,以便所有类别并排?
- python - Python - 使用 re.sub 和 string.punctuation 从单词列表中去除标点符号
- android - Android Volley SlowRequests 问题
- ios - URLSessionDownloadDelegate 似乎不能很好地与不同的线程一起使用
- jmeter - Jmeter客户端证书设置给出403错误