javascript - 如何读取 json 文件并在单击按钮后写入 DOM?
问题描述
html文件:
<p>Click the button below, to load the speaker bio details</p>
<button id="loadLess">Load Prev name</button>
<button id="loadMore">Load Next Name</button>
<div id="update"></div>
<script src="index.js"></script>
js文件
let i = 0;
document.getElementById("loadMore").addEventListener("click", changeColor(json));
function changeColor(json) {
// window.alert(evt.currentTarget.myParam);
console.log("this");
console.log("thist" + json[1].name);
i = i + 1
document.getElementById('update').innerText = json[1].name;
}
document.getElementById("loadLess").addEventListener("click", changeKolor(json));
function changeKolor(json) {
i = i - 1;
// window.alert(evt.currentTarget.myParam);
document.getElementById('update').innerText = json[1].name;
}
window.onload = function () {
fetch("data.json")
.then(response => response.json())
.then(json => console.log(json));
};
json文件
[
{
"name":"Barot Bellingham name1",
"shortname":"Barot_Bellingham",
},
{
"name": "2222 name2",
"shortname": "2",
},
{
"name": "33 name3",
"shortname": "33",
}
]
这绝对是一个 DOM 错误,我无法修复。我可以读取 JSON,但无法将其写入 HTML DOM。如果用户单击下一个按钮,它应该跳转到下一个名称,如果单击上一个名称,它应该跳转到下一个名称,依此类推。
解决方案
有多个问题。
添加事件监听器
将addEventListener
事件绑定到函数。您实现它的方式,您已经执行changeColor(json)
以定义该功能,这将不起作用。
用这个:
document.getElementById("loadMore").addEventListener("click", function() { changeColor(json); });
...
document.getElementById("loadLess").addEventListener("click", function() { changeKolor(json);} );
错误的索引
在里面changeColor(...)
和 changeKolor(...)
你不使用当前索引,但总是使用 1. change json[1]
tojson[i]
来解决这个问题。
推荐阅读
- ruby - id 为 123 的用户没有正确更新 id 为 123 的项目
- python - 为什么 Requests 库无法读取源代码?
- wysiwyg - 如何在 react-quill Hooks 中添加 className="" 和自定义标签?
- java - 如何移动 3d 对象并将其 360 度旋转显示在 Vuforia for android 的跟踪图像顶部?
- javascript - Javascript JSON 解析 php base64(file_get_contents($file)) 响应
- json - 如何处理不同的 JSON 模式并分派 hem 以由正确的解析器处理?
- c++ - constexpr 函数中的非文字(通过 std::is_constant_evaluate)
- javascript - 搜索使用异步存储存储的项目
- .net-core - 为什么在 vs 代码(.NET Core)中调试时不构建 C# 代码?
- flutter - 如何在 Flutter 中像 Youtube 一样显示时间