我在回答这个问题时采取了一些自由度,因为我仍然不确定你的数据结构是什么样子,但希望这会有所帮助。
以下是您接收到的数据作为JSON,然后解析。它是包含country_name
和info
属性的对象数组。
const countryInfo = [
{ country_name: 'Denmark', info: 'This is Denmark' },
{ country_name: 'England', info: 'This is England' },
{ country_name: 'Japan', info: 'This is Japan' }
];
有关此DEMO目的,我们抢body
元素,然后抢只是从数据的国名的数组。
const body = document.querySelector('body');
const names = countryInfo.map(obj => obj.country_name);
我们建立一些标志物与阵列中的数据,并将它们添加到body
元素。请注意数据属性data-name
。我们在这里存储国名的副本。
names.forEach(name => {
const html = `<div class="sitemark" data-name="${name}">${name}</div>`;
body.insertAdjacentHTML('beforeend', html);
});
我们抓住info
元素。这是我们添加国家信息的地方。
const info = document.querySelector('#info');
我们抓住标记并向它们添加事件监听器。点击时,请拨打displayData
功能。
const sitemarks = document.querySelectorAll('.sitemark');
sitemarks.forEach(marker => {
marker.addEventListener('click', displayData, false);
});
要得到我们的countryInfo
阵列拉出的第一个对象实例,其中国家名称相同的元素上的data-name
属性名称上进行find
操作countryinfo,然后取info
来自该对象的值。然后我们将该文本添加到info
元素。
function displayData() {
const text = countryInfo.find(obj => obj.country_name === this.dataset.name).info;
info.innerHTML = text;
}
请编辑您的问题以正确显示您的数据结构。您的代码似乎使用的是一组对象,而不是JSON([JSON是一种文本格式](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) )),所显示的代码似乎在修改数据,而不是显示任何内容。这将有助于在上下文中显示代码 - 从使用'return'看来它是一个函数,所以显示函数以及如何调用它。 – nnnnnn
请分享json reponse – brk
@nnnnnn你去我已编辑我的代码 – Kyle