我正在嘗試這樣做,以便單擊串列中的任何專案然后根據我定義的物件在另一個部分中回傳一個值。在這種情況下,單擊 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;
}
uj5u.com熱心網友回復:
我認為基本問題是,當您嘗試設定 innerHTML 時,您需要使用countryData[testValue]not countryData.testValue。第一個將查找作為變數值的鍵testValue。第二個將查找不在您的資料集中的“testValue”鍵。
此外,當您添加事件偵聽器時,您正在呼叫displayNarrative,而不是將該事件傳遞給將在單擊時執行的函式。
這是一個稍微添加的作業解決方案。我添加了 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/485960.html
標籤:javascript html 目的 dom
