我正在尝试这样做,以便单击列表上的任何项目然后根据我定义的对象在另一个部分中返回一个值。在这种情况下,单击 countryName 应该会在另一个部分显示 infoNarrative。
到目前为止,这是我所了解的(我显然是 HTML/Javascript 的初学者,解决这些问题对我的学习很有帮助)。请随时提出任何更聪明的建议,我也很乐意学习其他简单的方法。
HTML
<div class="sidebar">
<div class="heading">
<h1>Countries</h1>
</div>
<ul class="countryList">
<li id = "afghanistan">Afghanistan</li>
<li id = "bangladesh">Bangladesh</li>
</ul>
<div id="narrative" class="narrative">
Narrative Should Turn Up Here</div>
Javascript
'afghanistan': {
countryName: 'Afghanistan',
'infoNarrative': 'afg lorem ipsum dolor sit amet',
'link': 'google.com'
},
'bangladesh': {
countryName: 'Bangladesh',
'infoNarrative': 'bgd lorem ipsum dolor sit amet',
'link': 'google.com'
}
};
document.getElementById("afghanistan").addEventListener("click", displayNarrative());
function displayNarrative(testValue) {
document.getElementById("narrative").innerHTML = countryData.testValue.infoNarrative;
}
我认为基本问题是,当您尝试设置 innerHTML 时,您需要使用countryData[testValue]
not countryData.testValue
。第一个将查找作为变量值的键testValue
。第二个将查找不在您的数据集中的“testValue”键。
此外,您displayNarrative
在添加事件侦听器时调用,而不是向该事物传递将在单击时执行的函数。
这是一个稍微添加的工作解决方案。我添加class="countryItem"
了 htmlli
标记,以便您可以轻松地选择列表中的所有项目并将事件侦听器附加到它们。
document.addEventListener("DOMContentLoaded", () => {
const countryData = {
afghanistan: {
countryName: "Afghanistan",
infoNarrative: "afg lorem ipsum dolor sit amet",
link: "google.com"
},
bangladesh: {
countryName: "Bangladesh",
infoNarrative: "bgd lorem ipsum dolor sit amet",
link: "google.com"
}
};
const items = document.getElementsByClassName('countryItem')
Array.from(items).forEach(function(item) {
item.addEventListener('click', function() {
displayNarrative(item.id)
})
})
function displayNarrative(countryKey) {
const countryInfo = countryData[countryKey]
document.getElementById("narrative").innerHTML =
countryInfo.infoNarrative;
}
});
<div class="sidebar">
<div class="heading">
<h1>Countries</h1>
</div>
<ul class="countryList">
<li class="countryItem" id="afghanistan">Afghanistan</li>
<li class="countryItem" id="bangladesh">Bangladesh</li>
</ul>
<div id="narrative" class="narrative">
Narrative Should Turn Up Here</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句