首页 > 解决方案 > 如何读取 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。如果用户单击下一个按钮,它应该跳转到下一个名称,如果单击上一个名称,它应该跳转到下一个名称,依此类推。

标签: javascriptdom

解决方案


有多个问题。

添加事件监听器

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]来解决这个问题。


推荐阅读